-1

I've had help here Inserting and Updating data to MDB but still have a problem with update

I have an access mdb file with table "Table1" and 3 colums

ID
INFO 
TEXT

I can add new info, find info but the update gives me an unknown error. Something is wrong with the command I sent.

 con = new OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0; Data Source = c:\\mdb\\testmdb.mdb");
 cmd = new OleDbCommand();
 cmd.Connection = con;
    cmd.CommandText = "UPDATE Table1 SET Info = @Info, text = @text WHERE ID = @ID;";
    cmd.Parameters.AddWithValue("@ID", textBox1.Text);
    cmd.Parameters.AddWithValue("@Info", textBox2.Text);
    cmd.Parameters.AddWithValue("@text", textBox3.Text);
    con.Open(); // open the connection
    int numAffected = cmd.ExecuteNonQuery();
    con.Close();
Community
  • 1
  • 1
Iakovl
  • 1,013
  • 2
  • 13
  • 20

1 Answers1

4

The OleDbCommand does not support named parameters. This:

"UPDATE Table1 SET Info = @Info, text = @text WHERE ID = @ID;";

is equivalent to this:

"UPDATE Table1 SET Info = ?, text = ? WHERE ID = ?;";

and when you add parameters to the Parameters collection they are assigned in the order they are added. So the first parameter added will be assigned to the first placeholder, the second parameter to the second etc. You may use names for the placeholders for readability purposes but they do not matter when assigning values.

So you need to change the order in which you add the values to match the order in your query:

cmd.Parameters.AddWithValue("@Info", textBox2.Text);
cmd.Parameters.AddWithValue("@text", textBox3.Text);
cmd.Parameters.AddWithValue("@ID", textBox1.Text);
ChrisWue
  • 18,612
  • 4
  • 58
  • 83