I am working with the following set-up:
Consider two MySQL databases: abc
and xyz
, each with their own table: abc
. table_in_abc
and xyz
. table_in_xyz
. I need to run a simple MySQL query that select elements from the table_in_abc
with a JOIN relationship to table_in_xyz
.
In Workbench, the following query works fine:
SELECT AB.* , XY.*
FROM `abc`.`table_in_abc` AB
LEFT JOIN `xyz`.`table_in_xyz` XY ON AB.`ID` = XY`ID`
I am trying to achieve the same things in VBA. I am able to run a MySQL query on a single database (see example below) but unable to do so when the query involves multiple databases.
Example of simple VBA query on single database:
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 `abc`.`table_in_abc` WHERE `ID`=" & ID & ";"
rs1.Open sqlstr, conn, adOpenStatic
With Worksheets("Main").Cells(a, 1)
.ClearContents
.CopyFromRecordset rs1
End With
rs1.Close
Set rs1 = Nothing
I found a way to solve my above problem by simply setting two connections to the two different databases (working on the same MySQL instance).
My code looks like that :
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 conn2 = New ADODB.Connection
conn2.Open "DRIVER={MySQL ODBC 5.3 Unicode Driver}" _
& ";SERVER=" & server_name _
& ";DATABASE=" & database_name2 _
& ";UID=" & user_id2 _
& ";PWD=" & password2 _
& ";OPTION=3" '
' SELECT Query with LEFT JOIN on the two different databases
Set rs1 = New ADODB.Recordset
sqlstr = "SELECT AB.* , XY.* FROM `abc`.`table_in_abc` AB LEFT JOIN `xyz`.`table_in_xyz` XY ON AB.`ID` = XY`ID`"
rs1.Open sqlstr, conn, adOpenStatic
With Worksheets("main").Cells(1, 1)
.ClearContents
.CopyFromRecordset rs1
End With
rs1.Close
Set rs1 = Nothing
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.