UPDATE语句VS 2015中的语法错误

时间:2015-11-02 20:26:01

标签: c# visual-studio-2015 ms-access-2013

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

2 个答案:

答案 0 :(得分:1)

您错过了多个'声明,'后还有一个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?

答案 1 :(得分:0)

这是您的问题的解决方案,但我更希望您为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 + "'";