问题
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:
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;
- Can we stop using AddWithValue() already?
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();
}
来源:https://stackoverflow.com/questions/27103913/issue-in-updating-ms-access-records-using-oledbcommand-executenonquery-result