2014-07-17 51 views
0

所以,我對C#很陌生。我的頁面上有一個gridview行。一旦我編輯了數據,我希望它在鏈接到它的訪問數據庫中更新。我得到這個錯誤:UPDATE語句中的語法錯誤。我認爲我的約會是應該責備的,但仍然...我無法找出我做錯了什麼。 下面是我的更新行函數的代碼:在C#中的UPDATE語句中的語法錯誤asp.net

protected void OnUpdate(object sender, EventArgs e) 
{ 
     GridViewRow row = (sender as LinkButton).NamingContainer as GridViewRow; 
     string id = (row.Cells[0].Controls[0] as TextBox).Text; 
     string nume = (row.Cells[1].Controls[0] as TextBox).Text; 
     string prenume = (row.Cells[2].Controls[0] as TextBox).Text; 
     string data = (row.Cells[3].Controls[0] as TextBox).Text; 
     DataTable dt = ViewState["dt"] as DataTable; 
     //dt.Rows[row.RowIndex]["ID"] = id; 
     dt.Rows[row.RowIndex]["Nume"] = nume; 
     dt.Rows[row.RowIndex]["Prenume"] = prenume; 
     dt.Rows[row.RowIndex]["Data Nasterii"] = data; 
     ViewState["dt"] = dt; 
     GridView1.EditIndex = -1; 

     OleDbConnection con; // create connection 
     OleDbCommand com; // create command 

     con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\db\db1.mdb"); 

     con.Open(); 
     DateTime date = Convert.ToDateTime(data); 
     com = new OleDbCommand("Update Table1 set Nume=" + nume + " , Prenume=" + prenume + ", Data Nasterii= @date where ID=" + id, con); 
     com.Parameters.AddWithValue("@date", OleDbType.Date).Value=data; 
     com.ExecuteNonQuery(); 
     con.Close(); 

     this.BindGrid(); 
     Response.Write("alert('DATA UPDATED')"); 

} 

誰能幫助我?

回答

4

如果您的列名有兩個單詞,您需要使用方括號。喜歡;

[Data Nasterii] = @date 

重要的是,你應該總是使用parameterized queries。這種字符串連接對於SQL Injection攻擊是開放的。

我看到你參數化了你的data值,並參數化你的其他值。

同樣使用using statement來處置您的OleDbConnectionOleDbCommand

using(OleDbConnection con = new OleDbConnection(conString)) 
using(OleDbCommand cmd = con.CreateCommand()) 
{ 
    // Set your CommandText property. 
    // Define and add your parameter values. 
    // Open your OleDbConnection. 
    // Execute your query. 
}