我在使用Parameters.AddWithValues更新Access数据库中的多个列时遇到问题。
private void button2_Click(object sender, EventArgs e)
{
try
{
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.Parameters.AddWithValue("@Pin", textBox1.Text);
cmd.Parameters.AddWithValue("@EmployeeID", textBox2.Text);
cmd.Parameters.AddWithValue("@Email", textBox3.Text);
string query = "UPDATE UserInformation SET Pin = @Pin, Email = @Email Where EmployeeID = @EmployeeID";
cmd.CommandText = query;
cmd.ExecuteNonQuery();
}
catch
{
MessageBox.Show("Could not update database", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
con.Close();
}
}
我能够取出我的字符串中的一个参数,它更新得很好。例如:
UPDATE UserInformation SET Pin = @Pin WHERE EmployeeID = @EmployeeID
这样可以正常工作,但是当我添加一秒来更新时:
UPDATE UserInformation SET Pin = @Pin, Email = @Email WHERE EmployeeID = @EmployeeID
它不起作用。
这只是我查询字符串的一小部分;我有大约8-10项要更新。有什么建议吗?
答案 0 :(得分:1)
OleDbCommand
不支持命名参数。因此,您可以将其替换为?
。例如:
UPDATE UserInformation SET Pin = ?, Email = ? WHERE EmployeeID = ?
当然这意味着您的AddWithValue
方法现在需要按正确的顺序排列,这就是您的代码不起作用的原因 - 它将textBox3.Text
(即电子邮件)的值分配给@EmployeeID
参数。所以,订单应该是:
cmd.Parameters.AddWithValue("@Pin", textBox1.Text);
cmd.Parameters.AddWithValue("@Email", textBox3.Text);
cmd.Parameters.AddWithValue("@EmployeeID", textBox2.Text);
而且,我将重申这一点:Please don't use AddWithValue
at all