UPDATE语句VS 2015中的语法错误
本文关键字:语法 错误 2015 语句 VS UPDATE | 更新日期: 2023-09-27 18:20:12
每当我尝试更新Access数据库中的信息时,我都会在UPDATE
语句中得到语法错误。我试过移动东西,添加逗号或去掉逗号。我被卡住了,有什么建议吗?错误附加到底部的第二个cmd.ExecuteNonQuery();
。
if (txtdateId.Text != "")
{
if (txtdateId.IsEnabled == true)
{
cmd.CommandText =
"insert into tbEmp(DateofService, AssociateName, DeviceType, DeviceModel, Serial, Issue, Part1, Part2, Part3, RepairedBy, Campus) Values('" +
txtdateId.Text + "','" + txtEmpName.Text + "','" + txtContact.Text + "','" + txttype.Text +
"','" + txtserial.Text + "','" + txtAddress.Text + "','" + txtpart1.Text + "','" + txtpart2.Text +
"','" + txtpart3.Text + "','" + txtrepaired.Text + "','" + txtcampus.Text + "')";
cmd.ExecuteNonQuery();
BindGrid();
MessageBox.Show("Device Added Successfully");
ClearAll();
}
else
{
cmd.CommandText = "update tbEmp set DateofService = ,'" + txtdateId.Text + ",AssociateName = '" + txtEmpName.Text + ",DeviceType = '" + txtContact.Text + ",DeviceModel = '" + txttype.Text + ",Serial = '" + txtserial.Text + ",Issue = '" + txtAddress.Text + ",Part1 = '" + txtpart1.Text + ",Part2 = '" + txtpart2.Text + ",Part3 = '" + txtpart3.Text + ",RepairedBy = '" + txtrepaired.Text + "where Campus = '" + txtcampus.Text;
cmd.ExecuteNonQuery();
BindGrid();
MessageBox.Show("Device updated");
ClearAll();
}
}
您在声明中遗漏了几个'
,在DateofService
之后还有一个额外的'
。你的声明应该是这样的:
cmd.CommandText = "update tbEmp set DateofService = '" + txtdateId.Text + "',AssociateName = '" + txtEmpName.Text + "' , ...
此外,我强烈建议您使用parameterized queries
来避免SQL Injection
,如下所示:
在SQL中:
cmd.CommandText = "update tbEmp set DateofService = @txtdateId ,...";
cmd.Parameters.AddWithValue("txtdateId",txtdateId.Text);
对于Access和OleDB:
cmd.CommandText = "update tbEmp set DateofService = ? , ....";
cmd.Parameters.AddWithValue("DateofService ",txtdateId.Text);
虽然直接指定类型并使用Value属性比AddWithValue
更好。检查此项:Can we stop using AddWithValue() already?
这是您的问题的解决方案,但我更希望您为SQL注入做一些添加验证。首先获取文本框值验证它,然后传递查询。
cmd.CommandText = "update tbEmp set DateofService = '" + txtdateId.Text + "' ,AssociateName = '" + txtEmpName.Text + "' ,DeviceType = '" + txtContact.Text + "',DeviceModel = '" + txttype.Text + "',Serial = '" + txtserial.Text + "',Issue = '" + txtAddress.Text + "',Part1 = '" + txtpart1.Text + "',Part2 = '" + txtpart2.Text + "' ,Part3 = '" + txtpart3.Text + "' ,RepairedBy = '" + txtrepaired.Text + "' where Campus = '" + txtcampus.Text + "'";