0

I check my SQL Statement many times and it seems that my SQL Statement is Error. I don't why it doesn't work. My SQL Statement is correct and It resulted to this OleDBException "Syntax error in UPDATE statement.".

Here is the code

   OleDbConnection CN = new OleDbConnection(mysql.CON.ConnectionString);
   CN.Open();
   cmd1 = new OleDbCommand("Update Mosque Set Name='" + txtNAME.Text + "', No='" + Convert.ToInt32(txtNO.Text) + "', place='" + txtPlace.Text + "', group='" + txtGroup.Text + "', description='" + txtdec.Text + "' where  id='" + txtID.Text + "'", CN);
   cmd1.ExecuteNonQuery();
   CN.Close();

need help please to know what is the error here

4

2 回答 2

7

I don't know what database are you using, but I am sure that GROUP is a reserved keyword in practically any existant SQL database. This word cannot be used without some kind of delimiter around it. The exact kind of delimiter depend on the database kind. What database are you using?

Said that, please do not use string concatenation to build sql commands, but use always a parameterized query. This will allow you to remove any possibilities of Sql Injection and avoid any syntax error if one or more of your input string contains a single quote somewhere

So, supposing you are using a MS Access Database (In Access also the word NO is a reserved keyword and the delimiters for reserved keywords are the square brakets) you could write something like this

string commandText = "Update Mosque Set Name=?, [No]=?, place=?, " + 
                     "[Group]=?, description=? where  id=?"
using(OleDbConnection CN = new OleDbConnection(mysql.CON.ConnectionString))
using(OleDbCommand cmd1 = new OleDbCommand(commandText, CN))
{
    CN.Open();
    cmd1.Parameters.AddWithValue("@p1",txtNAME.Text);
    cmd1.Parameters.AddWithValue("@p2",Convert.ToInt32(txtNO.Text));
    cmd1.Parameters.AddWithValue("@p3",txtPlace.Text);
    cmd1.Parameters.AddWithValue("@p4",txtGroup.Text);
    cmd1.Parameters.AddWithValue("@p5",txtdec.Text);
    cmd1.Parameters.AddWithValue("@p6",txtID.Text);
    cmd1.ExecuteNonQuery();
} 

Instead for MySQL you have to use the backticks around the GROUP keyword

string commandText = "Update Mosque Set Name=?, No=?, place=?, " + 
                     "`Group`=?, description=? where  id=?"
于 2013-09-26T19:46:34.600 回答
0

Hard to tell without knowing the values of the texboxes, but I suspect that one of them has an apostrophe which is causing an invalid syntax.

I recommend using parameters instead:

   cmd1 = new OleDbCommand("Update Mosque Set [Name]=@Name, [No]=@No, [place]=@Place, [group]=@Group, [description]=@Description WHERE id=@ID", CN);
   cmd1.Parameters.AddWithValue("@Name",txtNAME.Text);
   cmd1.Parameters.AddWithValue("@No",Convert.ToInt32(txtNO.Text));
   // etc.
于 2013-09-26T19:48:34.243 回答