问题
Can anybody tell what is wrong in the following code ?
command.Connection = ConnectionManager.GetConnection();
command.CommandText = "Update Table1 SET Replaceme = ? WHERE Searchme = ?";
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("Replaceme", "Goodman");
command.Parameters.AddWithValue("Searchme", "Anand");
command.Connection.Open();
int recordsaffected = command.ExecuteNonQuery();
MessageBox.Show("Records affected : " + recordsaffected);
MessageBox
shows 0 records and it is actually not updating the record which is available.
Table name (Table1)
and Column names (Replaceme and Searchme)
are correctly spelled.
回答1:
First off, OleDbParameter
s are positional, not named. Read the Remarks section in the documentation. Disregard any answer that does not understand this.
Here's a minimal, working example.
First, create your database:


Second, write the code:
using System;
using System.Windows.Forms;
using System.Data.OleDb;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string connectionString;
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;";
connectionString += "Data Source=C:\\Temp\\Database1.mdb";
using (var connection = new OleDbConnection(connectionString))
{
connection.Open();
var command = connection.CreateCommand();
command.CommandText =
"UPDATE Table1 SET Replaceme = ? WHERE Searchme = ?";
var p1 = command.CreateParameter();
p1.Value = "Goodman";
command.Parameters.Add(p1);
var p2 = command.CreateParameter();
p2.Value = "Anand";
command.Parameters.Add(p2);
var result = String.Format("Records affected: {0}",
command.ExecuteNonQuery());
MessageBox.Show(result);
}
}
}
}
Result:


回答2:
Its not working because you are using ? instead of @ for the parametrized query.
Use this and it should work:
Update Table1 SET Replaceme = @Replaceme WHERE Searchme = @Searchme
来源:https://stackoverflow.com/questions/12226682/oledb-update-sql-with-parameter-value-not-updating-record-in-access