Issue in updating MS Access records using oledbcommand.executeNonQuery(), result not updating

930 views Asked by At

I am posting a query first time here, So, Please ignore my formatting.

I am trying to update my .accdb file using update command, but result of oledbcommand.executeNonQuery() is 0 hence result is not updating in the database.

Though I am receiving no errors.

Here is what I am doing.

string vsql = string.Format("UPDATE DefTask_List SET [Action]=@Action WHERE  [SNo]=@SNo");
vcom.Parameters.AddWithValue("@SNo", row.Cells[0].Value.ToString());
vcom.Parameters.AddWithValue("@Action", comboBox1.Text);

OleDbCommand vcom = new OleDbCommand(vsql, vcon);
vcon.Open();
int k = vcom.ExecuteNonQuery();
vcom.Dispose();
vcon.Close();

Please note that SNo is an autonumber in my .accdb file also with the same way I am inserting and deleting data but that is working fine.

1

There are 1 answers

1
Soner Gönül On BEST ANSWER

OleDbCommand doesn't support named parameters. The only matter is their orders.

From OleDbCommand.Parameters property

The OLE DB .NET Provider does not support named parameters for passing parameters...

Therefore, the order in which OleDbParameter objects are added to the OleDbParameterCollection must directly correspond to the position of the question mark placeholder for the parameter in the command text.

That's why your first @Action in OleDbCommand matches with @SNo in your AddWithValue and @SNo matches with your @Action in your AddWithValue.

Since probably you don't have a data like this, there will be no update operation.

Switch your parameter orders and use .Add method which is recommended instead of AddWithValue. It may generate unexpected results. Read;

Also use using statement to dispose your OleDbConnection and OleDbCommand instead of calling .Dispose() and .Close() methods manually.

using(OleDbConnection vcon = new OleDbConnection(conString))
using(OleDbCommand vcom = vcon.CreateCommand())
{
    vcom.CommandText = "UPDATE DefTask_List SET [Action]=@Action WHERE [SNo]=@SNo";
    vcom.Parameters.Add("?", OleDbType.VarChar).Value = comboBox1.Text;
    vcom.Parameters.Add("?", OleDbType.Integer).Value = (int)row.Cells[0].Value;
    // I assume your column types are NVarchar2 and Int32
    vcon.Open();
    int k = vcom.ExecuteNonQuery();
}