Syntax error in INSERT INTO statement generated by OleDbCommandBuilder

六月ゝ 毕业季﹏ 提交于 2021-02-08 04:22:18

问题


Why does this keep telling me

Syntax error in INSERT INTO statement

I searched for more details but it keeps telling me this.

This is the code :

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:


Some of your field names are reserved words in Access SQL (Date, Order) and you also have a field name with spaces in it. The default configuration of the CommandBuilder will not produce valid SQL statements in cases like this.

To fix this issue, immediately after the line...

Dim cb As New OleDb.OleDbCommandBuilder(da)

...add the following two lines:

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

That will tell the command builder to enclose table and field names in square brackets ([]) so instead of generating a statement like

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

it will generate a statement like

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

Those square brackets are required for the SQL statement to be syntactically correct.



来源:https://stackoverflow.com/questions/21880239/syntax-error-in-insert-into-statement-generated-by-oledbcommandbuilder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!