Excel - SQL' INSERT INTO'查询语法错误

时间:2017-06-05 16:25:12

标签: sql excel vba ms-access

我尝试使用Excel中的数据对MS Access数据库进行简单的插入查询。我使用带有硬编码值的参数化查询进行测试。直接在Access中运行查询,但尝试通过VBA执行它会导致语法错误。查询当前正在插入除Access表中自动生成的ID之外的每个字段。

Sub Test_SQL()
    Dim conn As ADODB.Connection
    Dim cmd As ADODB.Command
    Dim result
    Dim id As Integer

    Dim year As Integer
    Dim month As String
    Dim combocode As String
    Dim credamt As Double
    Dim qty As Integer
    Dim itemcode As String
    Dim sepbundleamt As Double
    Dim prodname As String

    '*********query variables********************
    year = 2017
    month = "July"
    combocode = "COMBCOD1"
    credamt = 420
    qty = 21
    itemcode = "ITEMCOD1"
    sepbundleamt = 12
    prodname = "Test Product"

    '********open DB connection and execute insertion******
    On Error GoTo ErrorHandler

    Set conn = New ADODB.Connection
    Set cmd = New ADODB.Command
    With conn
        .Provider = "Microsoft.ACE.OLEDB.12.0;"
        .ConnectionString = [redacted]
        .Open
    End With

    With cmd
        .ActiveConnection = conn
        .CommandType = adCmdText
        .CommandText = "INSERT INTO SB_DSLR (Year, Month, ComboCode, CreditAmt, Qty, ItemCode, SepBundleAmt, ProductName) VALUES (?,?,?,?,?,?,?,?);"
    End With
    With cmd.Parameters
        .Append cmd.CreateParameter("Year", adInteger, adParamInput, 4, year)
        .Append cmd.CreateParameter("Month", adWChar, adParamInput, 10, month)
        .Append cmd.CreateParameter("ComboCode", adWChar, adParamInput, 10, combocode)
        .Append cmd.CreateParameter("CreditAmt", adDouble, adParamInput, 10, credamt)
        .Append cmd.CreateParameter("Qty", adInteger, adParamInput, 10, qty)
        .Append cmd.CreateParameter("ItemCode", adWChar, adParamInput, 8, itemcode)
        .Append cmd.CreateParameter("SepBundleAmt", adDouble, adParamInput, 10, sepbundleamt)
        .Append cmd.CreateParameter("ProductName", adWChar, adParamInput, 100, prodname)
    End With

    cmd.Execute 
    conn.Close
    Set cmd = Nothing
    Exit Sub

ErrorHandler:
    MsgBox (Err.Number & ": " & Err.Description)
    If conn.State = adStateOpen Then
        conn.Close
    End If
    Set cmd = Nothing
End Sub

1 个答案:

答案 0 :(得分:2)

这种一般错误有多种原因,但同样的查询在MSAccess.exe中工作的事实表明保留字是原因。

的确,Jet reserved wordsMS Access reserved word。两者都是其他方法的命名函数和参数。有时.exe可以是宽松的,而ODBC连接则更具限制性。因此,考虑用反引号或方括号转义这些单词,或者完全避免使用这些单词。

.CommandText = "INSERT INTO SB_DSLR (`Year`, `Month`, ComboCode, CreditAmt, Qty, ItemCode, SepBundleAmt, ProductName) VALUES (?,?,?,?,?,?,?,?);"

.CommandText = "INSERT INTO SB_DSLR ([Year], [Month], ComboCode, CreditAmt, Qty, ItemCode, SepBundleAmt, ProductName) VALUES (?,?,?,?,?,?,?,?);"