Diana Veronica Hava
Diana Veronica Hava

Reputation: 3

Syntax error in UPDATE statement in C# asp.net

So, I'm quite new to C#. I have a a gridview row on my page. 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. 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?

Upvotes: 0

Views: 520

Answers (1)

Soner Gönül
Soner Gönül

Reputation: 98750

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.

I see you parameterized your data value, parameterize your other values as well.

Also use using statement to dispose your OleDbConnection and OleDbCommand.

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.
}

Upvotes: 4

Related Questions