OleDbCommandBuilder生成的INSERT INTO语句中的语法错误

时间:2014-02-19 12:16:40

标签: vb.net ms-access syntax-error oledb

为什么这会一直告诉我

  

INSERT INTO语句中的语法错误

我搜索了更多细节,但它一直告诉我这个。

这是代码:

Imports System.Data
Imports System.Data.OleDb
Public Class f9
    Dim ds As New DataSet
    Dim da As OleDb.OleDbDataAdapter

    Dim con As New OleDb.OleDbConnection
    Dim dbProvider As String
    Dim dbSource As String

    Dim sql As String


    Private Sub f9_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        dbProvider = "Provider=Microsoft.Jet.OLEDB.4.0;"
        dbSource = "Data Source = E:\21.mdb"

        con.ConnectionString = dbProvider & dbSource
        con.Open()

        sql = "SELECT * FROM snack"
        da = New OleDb.OleDbDataAdapter(sql, con)
        da.Fill(ds, "snack")

        da = New OleDb.OleDbDataAdapter(sql, con)

    End Sub
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles b1.Click
        Me.Close()
        x = x + (5 * 1)
        If d.tc.Text = f7.b1.Text Then
            Dim cb As New OleDb.OleDbCommandBuilder(da)
            Dim dsNewRow As DataRow

            dsNewRow = ds.Tables("snack").NewRow()

            dsNewRow.Item("Date") = f1.d1.Text
            dsNewRow.Item("Order") = d.tc.Text
            dsNewRow.Item("Number Of Items") = b1.Text
            dsNewRow.Item("Price") = " 5 "
            dsNewRow.Item("Total") = x
            ds.Tables("snack").Rows.Add(dsNewRow)
            da.Update(ds, "snack")
            con.Close()
        End If




    End Sub


End Class

1 个答案:

答案 0 :(得分:3)

您的一些字段名称在Access SQL(DateOrder)中为reserved words,并且您还有一个包含空格的字段名称。在这种情况下,CommandBuilder的默认配置不会生成有效的SQL语句。

要解决此问题,请紧接在行...

之后
Dim cb As New OleDb.OleDbCommandBuilder(da)

...添加以下两行:

cb.QuotePrefix = "["
cb.QuoteSuffix = "]"

这将告诉命令构建器将表和字段名称括在方括号([])中,而不是生成类似

的语句
INSERT INTO snack (Date, Order, Number Of Items) VALUES ...

它会生成一个类似

的语句
INSERT INTO [snack] ([Date], [Order], [Number Of Items]) VALUES ...

这些方括号是SQL语句在语法上正确所必需的。