Click here to Skip to main content
15,884,176 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How to fix “System.Data.OleDb.OleDbException: 'Syntax error in UPDATE statement.'”?

What I have tried:

C#
public void btnUpdtLicens_Click_1(object sender, EventArgs e)
        {
            string conString = "Provider= Microsoft.Jet.OLEDB.4.0; Data Source=" + DBPath + ";";
            using (OleDbConnection con = new OleDbConnection(conString))
            {
                con.Open();
                if (con.State == ConnectionState.Open)
                {
                    foreach (DataGridViewRow row in LicenseAllctnGridView.Rows)
                    {

                        if (row.Cells[0].Value != null && row.Cells[1].Value != null)
                        {
                            OleDbDataAdapter _oda = new OleDbDataAdapter();
                            //string query = "update AllottedLicense set Department = " + row.Cells[0].Value.ToString() + ", AllottedLicense = " + row.Cells[1].Value.ToString() + ", where Department = " + row.Cells[0].Value.ToString() + "; ";
                            OleDbCommand cmd = new OleDbCommand("update AllottedLicense set Department = " + row.Cells[0].Value.ToString() + ", AllottedLicense = " + row.Cells[1].Value.ToString() + ", where Department = " + row.Cells[0].Value.ToString() + "", con);
                            _oda.SelectCommand = cmd;
                            cmd.ExecuteNonQuery();
                            cmd.Parameters.Clear();
                        }
                    }

                }
                con.Close();
        }
    }
Posted
Updated 3-Mar-21 8:48am
v2
Comments
[no name] 3-Mar-21 13:32pm    
You had a string you could display and then use ... and then you don't. The mind boggles.

1 solution

Because you are concatenating your sql statement together you are probably missing a single quote or your data has a quote in it which breaks the sql statement. It would be very easy to debug your code and see what the UPDATE statement actually looks like.

To fix this you should use parameterized queries. For example:

C#
String sql = "UPDATE table SET field = @value1";
using (SqlCommand cmd = new SqlCommand(sql, sqlCon){
  cmd.Parameters.AddWithValue("@value1", row.Cells[0].Value.ToString());
   ...
}
 
Share this answer
 
Comments
Member 15088142 4-Mar-21 1:05am    
I got the output i put one extra comma before where condition thanks you
shanda watkins 4-Mar-21 6:56am    
You're welcome.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900