我正在尝试使用Connected Architecture的OleDbCommand类删除Access数据库的记录
using System.Data.OleDb;
using System.Data;
protected void Button2_Click(object sender, EventArgs e)
{
String x = "Connection String...";
OleDbConnection con = new OleDbConnection(x);
con.Open();
String query = "Delete FROM TB WHERE NO=@number";
OleDbCommand cmd = new OleDbCommand(query, con);
cmd.Parameters.AddWithValue("@number", TextBox2.Text);
int res = cmd.ExecuteNonQuery();
if (res > 0)
{
Label.Text = "Deleted successfully";
}
else
{
Label.Text = "Not Deleted";
}
con.Close();
}
每当我尝试删除记录Else Condition时,都会执行不删除的情况。
UPDATE查询同样的问题,
protected void Button3_Click(object sender, EventArgs e)
{
String x = "Connection String..";
OleDbConnection con = new OleDbConnection(x);
con.Open();
String query = "UPDATE TB SET NM = @name WHERE NO = @TextBox_NO";
OleDbCommand cmd = new OleDbCommand(query, con);
int res = cmd.ExecuteNonQuery();
if (res > 0)
{
Label.Text = "Updated successfully";
}
else
{
Label.Text = "Not Updated";
}
con.Close();
}
INSERT查询工作得很好。
我在哪里做错了?
最佳答案
前言:我对ASP.NET一无所知,但我确实知道MS Access。而NO
是reserved word。因此,如果使用保留字,则在引用为字段时可能会导致意外的答案或错误。
要解决此问题,请考虑在删除和更新查询中将NO
列括入括号。
String query = "DELETE FROM TB WHERE [NO] = @number"
String query = "UPDATE TB SET NM = @name WHERE [NO] = @TextBox_NO"
我可以在Microsoft Access 2013的SQL查询中测试
NO
vs [NO]
列引用时确认此解决方案。前者返回零记录,而后者返回正确的记录。