我正在尝试从excel向mysql添加数据。我在这一行上遇到上述错误:rs.Open strSQL,oConn,adOpenDynamic,adLockOptimistic
这是我的代码:
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错误?
答案 0 :(得分: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