更新 ExceptionNonQuery
Update ExceptionNonQuery
我正在尝试更新 MS Access table,但它一直抛出错误:
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 注入),您需要开始使用参数
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();
}
我正在尝试更新 MS Access table,但它一直抛出错误:
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 注入),您需要开始使用参数
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();
}