【问题标题】:Syntax error in query [duplicate]查询中的语法错误[重复]
【发布时间】:2015-10-09 23:48:52
【问题描述】:
With cmd
    .Connection = con
    .CommandTimeout = 0
    .CommandText = "INSERT INTO tableContacts (NameUser, Address, City, Phone, Fax, Note, Email) VALUES (@NameUser, @Address, @City, @Phone, @Fax, @Note, @Email)"
    With .Parameters
        .AddWithValue("@NameUser", txtName.Text)
        .AddWithValue("@Address", txtAddress.Text)
        .AddWithValue("@City", txtCity.Text)
        .AddWithValue("@Phone", txtPhone.Text)
        .AddWithValue("@Fax", txtFax)
        .AddWithValue("@Note", txtNote.Text)
        .AddWithValue("@Email", txtTo.Text)

    End With

    Try
        cmd.ExecuteNonQuery()
    Catch ex As Exception

    End Try
    .Dispose()
End With

找不到问题出在哪里。

调试器说的是:

{"INSERT INTO 语句中的语法错误。"}

【问题讨论】:

  • 这与@Email 无关,这是访问数据库
  • 对于那些投票关闭作为“错字问题”并支持相应 cmets 的人:如果它是关于缺少/无效的参数,则错误会有所不同。
  • Note 是保留字。您需要将其括在方括号 [Note] 中。 support.microsoft.com/en-us/kb/321266
  • @GSerg 我投票关闭它作为一个错字。我们不需要对每个保留字进行问答。如果您知道一个好的规范,请将 VTC 作为骗子。
  • @Bjørn-RogerKringsjå 好的,如果您 VTC 知道它与关键字有关,那是有道理的。接近投票出现在您的评论之前,因此看起来人们正在根据缺少的@ 进行 VTC。

标签: sql vb.net ms-access


【解决方案1】:

OleDbCommands 不支持命名参数。您需要在 SQL 语句中使用问号,然后按正确的顺序添加参数。

.CommandText = "INSERT INTO tableContacts (NameUser, Address, City, Phone, Fax, Note, Email) VALUES (?, ?, ?, ?, ?, ?, ?)"
With .Parameters
    .AddWithValue("?", txtName.Text)
    .AddWithValue("?", txtAddress.Text)
    .AddWithValue("?", txtCity.Text)
    .AddWithValue("?", txtPhone.Text)
    .AddWithValue("?", txtFax)
    .AddWithValue("?", txtNote.Text)
    .AddWithValue("?", txtTo.Text)
End With

【讨论】:

  • 虽然 OleDb 不支持命名参数是对的,但 OP 的代码是 work anyway。这不是问题的根源。
  • 当您的语句在 SQL 语句中使用 @ 作为参数前缀时,您确实会遇到语法错误。使用保留字也可以做到这一点。
  • 只有在您实际手动发送查询文本中的@ 时才会如此。当您有一个使用@ 构造的命令对象时,@ 不一定会到达数据库。
猜你喜欢
  • 2016-10-16
  • 1970-01-01
  • 2014-04-17
  • 1970-01-01
  • 1970-01-01
  • 2013-08-22
  • 1970-01-01
  • 2019-01-02
  • 1970-01-01
相关资源
最近更新 更多