表达式中缺少运算符?

时间:2014-03-28 15:47:26

标签: sql vb.net

很明显,它说我在查询中错过了一个操作符,但我无法找到位置?

Dim updateStatement As String =
        "UPDATE Customers SET " &
        "Name = """ & txtName.Text & ", """ &
        "Address = """ & txtAddress.Text & ", """ &
        "City = """ & txtCity.Text & ", """ &
        "State = """ & txtState.Text & ", """ &
        "ZipCode = """ & txtZipCode.Text & ", """

出现错误如下:

A first chance exception of type 'System.Data.OleDb.OleDbException' occurred in
System.Data.dll

Additional information: 
Syntax error (missing operator) in query expression 
'"Johnson, Ajith, "Address = "2200 Old Germantown Road, "City = "McGregor, 
"State = "CA, "ZipCode = "55555          , "'.

请注意,当我尝试更新记录

时会发生这种情况

编辑:我也没有使用AddWithValue。

编辑2:是的我知道这是一种不好的方法,但这就是教师想要的方式。

2 个答案:

答案 0 :(得分:3)

解决方案就是这样。

Dim updateStatement As String =
    "UPDATE Customers SET " &
    "Name = """ & txtName.Text & """, " &
    "Address = """ & txtAddress.Text & """, " &
    "City = """ & txtCity.Text & """, " &
    "State = """ & txtState.Text & """, " &
    "ZipCode = """ & txtZipCode.Text & """"

但正如其他人指出:从未使用过这个!

这是不可读的,不可维护的,并且存在SQL注入的危险。

请改用:

Dim updateStatement As String =
        "UPDATE Customers SET " &
        "Name = @name, Address = @address, City = @city, State = @state, ZipCode = @zipcode"

并在OleDbCommand中填写这些参数。如果您使用Access或类似,则应使用?而不是命名参数。

在生产环境中,您还喜欢使用参数的好处:您将从数据库中获得缓存执行计划等的可能性,因为语句的哈希值保持不变。因此,如果您运行1000次,数据库不需要重新考虑'如何执行此操作:性能提升!

答案 1 :(得分:0)

我永远不会教您使用字符串连接来构建sql语句。如果有人试图说服你并不重要,那么你应该指出他/ some page about Sql Injection

顺便说一下,你的错误可能是由ZipCode值末尾的逗号引起的。

请记住没有WHERE语句的UPDATE更新表中的所有记录

相反,您应该使用参数化查询

来编写UPDATE代码
    Dim updateStatement As String =
    "UPDATE Customers SET Name=?, " & _
    "Address = ?, City = ?, State = ?, ZipCode = ? " & _
    "WHERE YourPrimaryKeyField = ?"

    OleDbCommand cmd = new OleDbCommand(updateStatement, connection)
    cmd.Parameter.AddWithValue("@p1", txtName.Text)
    cmd.Parameter.AddWithValue("@p2", txtAddress.Text)
    cmd.Parameter.AddWithValue("@p3", txtCity.Text )
    cmd.Parameter.AddWithValue("@p4", txtState.Text )
    cmd.Parameter.AddWithValue("@p5", txtZipCode.Text )
    cmd.Parameter.AddWithValue("@p6", txtPrimaryKeyValue.Text)
    cmd.ExecuteNonQuery()

现在,从Sql Injection问题的一部分,查看查询文本。您是否认为这比上面的混乱连接更容易理解?