2015-11-02 68 views
0

每当我尝试更新Access数据库中的信息时,我都会在UPDATE语句中得到语法错误。我尝试过移动东西并添加逗号或取消逗号。我被卡住了,对我能做什么有任何建议?该错误附在底部的第二个cmd.ExecuteNonQuery();UPDATE语句中的语法错误VS 2015

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(); 
    } 
} 
+3

[SQL注入警报](http://msdn.microsoft.com/en-us/library/ms161953%28v=sql.105%29.aspx) - 你应该**不**连接在一起你的SQL语句 - 使用**参数化查询**来代替以避免SQL注入 –

回答

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); 

以及获得和OLEDB:

cmd.CommandText = "update tbEmp set DateofService = ? , ...."; 
cmd.Parameters.AddWithValue("DateofService ",txtdateId.Text); 

虽然直接指定类型并使用Va lue属性比AddWithValue更好。选中此项:Can we stop using AddWithValue() already?

+1

实际上,MS Access和OleDB不支持像** @ txtdateId这样的**命名**参数 - Access仅使用'?'和*位置*参数 –

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 + "'"; 
+0

这仍然缺少一些关闭单引号。 – juharr

+0

@juharr,谢谢。我刚刚更新 – Jigneshk