我通过VBA连接到MySQL数据库,但我无法确定从SHOW TABLES查询返回值的正确语法。
Dim rs As Object
Dim ws As Worksheet
Dim sqlstr As String
Set rs = CreateObject("ADODB.Recordset")
Set ws = ThisWorkbook.Worksheets(1)
sqlstr = "SHOW TABLES"
Call connectDatabase
rs.Open sqlstr, DBCONT
For i = 0 To (rs.RecordCount - 1)
ws.Cells(i+1, 1).value = rs(i)
rs.movenext
Next i
rs.Close
Set rs = Nothing
Call closeDatabase
错误声明读作:
运行时错误'3265' - 在集合中找不到项目 对应于请求的名称或序数。
当我尝试查看“SHOW COLUMNS FROM tableName
”查询以及“SELECT columnName1 FROM tableName
”查询的结果时,完全相同的代码可以正常运行。我假设错误是表名不应该作为Recordset ???
根据要求,这是我连接到我的数据库的方式:
Public DBCONT As Object
Public Function connectDatabase()
Set DBCONT = CreateObject("ADODB.Connection")
Dim Server_Name As String
Dim Database_Name As String
Dim User_ID As String
Dim Password As String
Dim Port As String
Dim sConn As String
Server_Name = "localhost"
Database_Name = "databaseName"
User_ID = "userID"
Password = "password"
Port = "3306"
sConn = "Driver={MySQL ODBC 5.1 Driver};Server=" & _
Server_Name & ";Database=" & Database_Name & _
";UID=" & User_ID & ";PWD=" & Password & ";Option=3;"
DBCONT.Open sConn
DBCONT.cursorlocation = 3
End Function
这就是我关闭数据库的方式:
Public Function closeDatabase()
On Error Resume Next
DBCONT.Close
Set DBCONT = Nothing
On Error GoTo 0
End Function
答案 0 :(得分:0)
barrowc在评论中回答:
一般情况下,您可以用ws.Cells(1, 1).CopyFromRecordset rs
替换整个For..Next循环。不确定它是否有助于解决此特定错误 - barrowc Apr 8 at 23:54