Question

I am Trying to Update multiple rows in a MS Access DB But every time it gives ERROR IN UPDATE SYNTAX here's my code

cn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source =C:\\Users\\Kalpesh\\Desktop\\Entry.accdb");
sqlstr = "Update Members SET Name=@Name, MobileNo=@MobileNo, Password=@Password, IDType=@IDType, IDNo=@IDNo, AmountPaid=@AmountPaid, Address=@Address, Reg Date = "+DateTime.Now.ToShortDateString()+" WHERE UserName = '" + comboBox4.SelectedItem.ToString() + "'",cn);
cmd = new OleDbCommand(sqlstr, cn);
cmd.Parameters.AddWithValue("@Name", textBox19.Text.ToString());
cmd.Parameters.AddWithValue("@MobileNo", textBox14.Text.ToString());
cmd.Parameters.AddWithValue("@Password", textBox17.Text.ToString());
cmd.Parameters.AddWithValue("@IDType", comboBox5.SelectedItem.ToString());
cmd.Parameters.AddWithValue("@IDNo", textBox11.Text.ToString());
cmd.Parameters.AddWithValue("@AmountPaid", textBox16.Text.ToString());
cmd.Parameters.AddWithValue("@Address", richTextBox3.Text.ToString());

cn.Open();
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
MessageBox.Show("Record Updated");
cn.Close();
Was it helpful?

Solution

Name and Password are reserved keywords in MS Access.

If a reserved word is already in use, you can avoid error messages by surrounding each occurrence of the word with brackets ([ ]). However, the best solution is to change the name to a nonreserved word.

You need to use Reg Date with square brackets like [Reg Date] also since it has space. Parameterized your Reg Date and UserName column values as you did for other columns. Like;

... [Reg Date] = @reg WHERE UserName = @user ...
cmd.Parameters.AddWithValue("@reg", DateTime.Now.ToShortDateString());
cmd.Parameters.AddWithValue("@user", comboBox4.SelectedItem.ToString());

Also use using statement to dispose your OleDbConnection and OleDbCommand.

string conString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source =C:\\Users\\Kalpesh\\Desktop\\Entry.accdb";
using(OleDbConnection cn = new OleDbConnection(conString))
using(OleDbCommand cmd = cn.CreateCommand())
{
  // Do your work..
}

OTHER TIPS

Since there is no clear error message about the syntax problem, I would guess its the lack of single quotes around the date, try this:

RegDate = '"+DateTime.Now.ToShortDateString()+"'

Problem is here

 "Reg Date = "+DateTime.Now.ToShortDateString()+"

Try this

 "[Reg Date] = #" + DateTime.Now.ToShortDateString() + "# "
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top