简体   繁体   English

C#asp.net中UPDATE语句中的语法错误

[英]Syntax error in UPDATE statement in C# asp.net

So, I'm quite new to C#. 因此,我对C#还是很陌生。 I have aa gridview row on my page. 我的页面上有一个gridview行。 Once I edit the data, I want it updated also in the access database that is linked to it. 编辑数据后,我还希望在链接到它的访问数据库中也更新它。 I get this error: Syntax error in UPDATE statement. 我收到此错误:UPDATE语句中的语法错误。 I think my date is the one to blame but still... I can't find out what I'm doing wrong. 我认为我的约会应该受到指责,但仍然...我无法找出我做错了什么。 Here's the code for my update row function: 这是我的更新行函数的代码:

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')");

}

Can anyone help me? 谁能帮我?

If your column name has two words, you need to use square brackets with it. 如果列名包含两个单词,则需要在其中使用方括号。 Like; 喜欢;

[Data Nasterii] = @date

But more important, you should always use parameterized queries . 重要的是,您应始终使用参数化查询 This kind of string concatenations are open for SQL Injection attacks. 这类字符串连接对SQL注入攻击开放。

I see you parameterized your data value, parameterize your other values as well. 我看到您参数化了您的data值,也参数化了您的其他值。

Also use using statement to dispose your OleDbConnection and OleDbCommand . 也可以使用using语句来处理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.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM