2010-05-12 67 views
1

我想從Excel中添加數據到MySQL。我收到上述錯誤在這條線:rs.Open STRSQL,oConn,adOpenDynamic,ADLOCKOPTIMISTIC從excel連接到mysql:ODBC驅動程序不支持請求的屬性

這裏是我的代碼:

Dim oConn As ADODB.Connection 

Private Sub ConnectDB() 
    Set oConn = New ADODB.Connection 
    oConn.Open "DRIVER={MySQL ODBC 5.1 Driver};" & _ 
     "SERVER=localhost;" & _ 
     "DATABASE=employees;" & _ 
     "USER=root;" & _ 
     "PASSWORD=some_pass;" & _ 
     "Option=3" 

End Sub 

Function esc(txt As String) 
    esc = Trim(Replace(txt, "'", "\'")) 
End Function 


Private Sub InsertData() 
Dim rs As ADODB.Recordset 
    Set rs = New ADODB.Recordset 
    ConnectDB 
    With wsBooks 
     For rowCursor = 2 To 11 
      strSQL = "INSERT INTO tutorial (author, title, price) " & _ 
       "VALUES ('" & esc(.Cells(rowCursor, 1)) & "', " & _ 
       "'" & esc(.Cells(rowCursor, 2)) & "', " & _ 
       esc(.Cells(rowCursor, 3)) & ")" 
      rs.Open strSQL, oConn, adOpenDynamic, adLockOptimistic 
     Next 
    End With 
End Sub 

什麼錯rs.Open STRSQL,oConn,adOpenDynamic,ADLOCKOPTIMISTIC? 爲什麼我得到odbc錯誤?

回答

3

INSERT不返回記錄集。使用oConn.Execute來做這種插入。

另一個選擇可能是這個特定版本的mysql驅動程序不支持adOpenDynamic(你確定你需要它?)或adLockOptimistic(相同)。

但無論如何,這段代碼是一個sql injection的洞。您應該考慮使用參數化查詢:

dim cm as adodb.command 
set cm=new adodb.command 
set cm.activeconnection = oConn 
cm.commandtype = adcmdtext 
cm.commandtext = "insert tutorial (author, title, price) values (?,?,?)" 
cm.parameters.add cm.createparameter(,adVarChar,adParamInput,50,esc(.Cells(rowCursor, 1))) 
cm.parameters.add cm.createparameter(,adVarChar,adParamInput,50,esc(.Cells(rowCursor, 2))) 
cm.parameters.add cm.createparameter(,adDouble,adParamInput,,esc(.Cells(rowCursor, 3))) 

cm.execute ,, adExecuteNoRecords 
相關問題