2013-04-15 39 views
-5

所以我有以下代碼,但數據庫沒有被更新,並且頁面似乎沒有顯示任何錯誤。沒有錯誤的內部,但仍然沒有數據進去。ButtonClick事件不添加數據

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Data.SqlClient; 
using System.Data; 

public partial class ValidateMe : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 
    } 

    protected void Button1_Click(object sender, EventArgs e) 
    { 
     SqlConnection connection = new SqlConnection("Data Source=MICROSOF-58B8A5\SQL_SERVER_R2;Initial Catalog=Movie;Integrated Security=True"); 

     connection.Open(); 

     if (TextBox8.Text == TextBox9.Text) 
     { 
      string UserName = TextBox7.Text; 
      string Password = TextBox8.Text; 
      string FirstName = TextBox1.Text; 
      string LastName = TextBox2.Text; 
      string Address = TextBox3.Text; 
      string PostCode = TextBox4.Text; 
      string Phone = TextBox5.Text; 
      string Email = TextBox6.Text; 

      string sqlquery = "INSERT INTO `users` (`user_id`, `username`, `first_name`, `last_name`, `password`, `address`, `postcode`, `phone`, `email`, `level`) VALUES (NULL, '@UserName', '@FirstName', '@LastName', '@Password', '@Address', '@PostCode', '@Phone', '@Email');"; 

      SqlCommand command = new SqlCommand(sqlquery, connection); 
     } 
    } 
} 

任何幫助我所缺少的將不勝感激。

+1

缺少什麼?構建一個命令,添加參數並執行? – Steve

+2

呃...這段代碼有太多錯誤。請在網上搜索如何使用c#將數據插入到數據庫中,因爲在這裏很難解決所有問題。你沒有關閉/處置連接,你沒有執行你已經準備好的命令,你沒有將參數傳遞到命令 - 這是首發。在網上會有足夠的信息讓你開始 - 這很簡單,所以不用擔心! – Pako

+0

不要忘記關閉連接;-)使用該命令使用參數並在參數綁定後執行它。 –

回答

2

您的代碼錯過了幾個(基本)步驟。

打開連接後,你應該做的:

  • 構建命令
  • 添加命令所需的參數
  • 執行它
  • 關閉像這樣的連接

string sqlquery = "INSERT INTO users (username, first_name, last_name, password," + 
        "address, postcode, phone, email, level) VALUES " + 
        "(@UserName, @FirstName, @LastName, @Password, " + 
        "@Address, @PostCode, @Phone, @Email);"; 

SqlCommand command = new SqlCommand(sqlquery, connection); 

command.Parameters.AddWithValue("@username", Username); 
..... 
// Add the other parameters 
..... 

// Execute the query 
command.ExecuteNonQuery(); 

// Close the connection 
connection.Close(); 

您不必在域名(SqlServer不需要它們)的位置加入反斜槓,也不應將參數名稱括在單引號中。

最後一個音符。如果user_id是標識字段,則不需要添加到commandtext。

+0

我已經添加了它,但我認爲SQL連接不起作用,因爲數據仍然不會進行 SqlConnection connection = new SqlConnection(「Data Source = MICROSOF-58B8A5/SQL_SERVER_R2; Initial Catalog = Movie ; Integrated Security = True「); –

+0

如果連接字符串中存在錯誤,那麼當您嘗試打開連接時應該有錯誤 – Steve