我正在尝试更新 MS Access 表,但它一直抛出错误:
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: Syntax error in string in query expression 'EmID = '234'.
EmID
在数据库中。请帮忙
public partial class Sales : Form
{
...
private void btnUpdate_Click(object sender, EventArgs e)
{
int EmpID = int.Parse(txtEmpID.Text);
OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\SalesData.mdb");
OleDbCommand update = new OleDbCommand("UPDATE Sales SET Printer = '" + txtPrinter.Text + "', Ink = '" +txtInk.Text + "', Paper = '"+txtPaper.Text+"' WHERE EmID = '" + txtEmpID.Text + " ", con);
con.Open();
update.ExecuteNonQuery();
con.Close();
MessageBox.Show("Sales Updated");
}
...
}
最佳答案
您忘记在 WHERE 值后添加结束引号。但是修复问题并添加缺失的引号只会掩盖其他问题。
如果您的某个文本框包含单引号怎么办?您将再次收到由字符串连接引起的语法错误异常,其中引号用作您的值的分隔符。如果您的用户输入单引号,您将再次混淆 Sql 解析器。
要解决这个问题(以及一个更严重的问题,称为 Sql 注入(inject)),您需要开始使用参数
string cmdText = @"UPDATE Sales SET Printer = @printer,
Ink = @Ink, Paper = @Paper
WHERE EmID = @id";
using(OleDbConnection con = new OleDbConnection(...))
using(OleDbCommand cmd = new OleDbCommand(cmdText, con))
{
con.Open();
cmd.Parameters.Add("@printer", OleDbType.VarWChar).Value = txtPrinter.Text;
cmd.Parameters.Add("@ink", OleDbType.VarWChar).Value = txtInk.Text;
cmd.Parameters.Add("@paper", OleDbType.VarWChar).Value = txtPaper.Text;
cmd.Parameters.Add("@id", OleDbType.VarWChar).Value = txtEmpID.Text;
cmd.ExecuteNonQuery();
}
关于c# - 更新 ExceptionNonQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37736594/