开发者

Excel VBA: Query a MySQL Database

开发者 https://www.devze.com 2023-01-27 05:46 出处:网络
I am looking for an example of how to query a MySQL database using Excel VBA. I am able to use Data \\ From Other Sources \\ From Microsoft Query to import data from the db, but w开发者_JAVA百科hat I

I am looking for an example of how to query a MySQL database using Excel VBA.

I am able to use Data \ From Other Sources \ From Microsoft Query to import data from the db, but w开发者_JAVA百科hat I am actually looking for is a way not to import it to a spreadsheet directly, but rather to a data structure in VBA for further manipulation before I output the result to the spreadsheet. How can I do this?


to connect:

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

then to query:

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


This works for me:

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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号