UPDATE 语句中的语法错误 VS 2015

Syntax Error in UPDATE statement VS 2015

每当我尝试更新 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 to avoid 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);

虽然直接指定类型并使用值 属性 比 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 + "'";