2010-11-29 214 views
1

我在查找如何使用Excel VBA查詢MySQL數據庫的示例。Excel VBA:查詢MySQL數據庫

我能夠使用數據\自其他來源\從微軟查詢從數據庫導入數據,但什麼我實際上是尋找一種方法不是直接將其導入到電子表格,而是轉換爲VBA中的數據結構,以便在將結果輸出到電子表格之前進一步處理。我怎樣才能做到這一點?

+0

如:http://stackoverflow.com/questions/2821718/excel-vba-writing-to-mysql-database/2821911#2821911? – Fionnuala 2010-11-29 16:46:22

回答

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 
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