2017-06-05 59 views
0

我正在嘗試使用Excel中的數據對MS Access數據庫進行簡單的插入查詢。我正在使用帶硬編碼值的參數化查詢進行測試。直接在Access中運行查詢,但試圖通過VBA執行它會導致語法錯誤。該查詢當前將插入Access表中除自動生成的ID以外的每個字段。Excel - SQL'INSERT INTO'查詢語法錯誤

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

你能分享你得到的確切的錯誤信息嗎? – Mureinik

+0

'-2147217900:INSERT INTO語句中的語法錯誤。' –

+2

如果您打印您的cmd文本,SQL會顯示什麼? –

回答

1

有針對一般性錯誤多種原因,但相同的查詢在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 (?,?,?,?,?,?,?,?);" 
+0

這是問題所在。謝謝! –

+0

太棒了!樂意效勞。請接受解決方案以確認解析。 – Parfait