Excel VBA:查询MySQL数据库

时间:2010-11-29 15:54:20

标签: mysql data-structures excel-vba database-connection vba

我正在寻找一个如何使用Excel VBA查询MySQL数据库的示例。

我可以使用 数据\来自其他来源\来自Microsoft Query 来从数据库导入数据,但我实际上正在寻找的方法是不要在将结果输出到电子表格之前,将其直接导入电子表格,而是导入VBA中的数据结构以进行进一步操作。我怎么能这样做?

2 个答案:

答案 0 :(得分:4)

连接:

conMySQL.ConnectionString = "DRIVER={MySQL ODBC 5.1 Driver};" & "SERVER=" & server & ";" & " DATABASE=" & database & ";" & "UID=" & login_user & ";PWD=" & password & "; OPTION=3; PORT=" & port & ";Connect Timeout=20;"

    'open the connection
    conMySQL.Open

然后查询:

strSQL = "SELECT x FROM some_table"
MySQL.Query (strSQL)

With rsTemporary
      Do Until .EOF
          recordCount = recordCount + 1
          some_variable = ![supcode]
          rsTemporary.MoveNext
      Loop
End With
        MySQL.closeCon

答案 1 :(得分:0)

这对我有用:

Set conn = New ADODB.Connection
conn.Open "DRIVER={MySQL ODBC 5.3 Unicode Driver}" _
& ";SERVER=" & server_name _
& ";DATABASE=" & database_name _
& ";UID=" & user_id _
& ";PWD=" & password _
& ";OPTION=3" '

Set rs1 = New ADODB.Recordset
sqlstr = "SELECT * FROM `table1` WHERE `ID`=" & ID & ";" 
rs1.Open sqlstr, conn, adOpenStatic
With Worksheets("Main").Cells(1, 1)
.ClearContents
.CopyFromRecordset rs1
End With
rs1.Close
Set rs1 = Nothing