我有一个查询,该查询将两个表中的列连接在一起。我在mySQL Workbench中运行查询时没有问题,但是当我在VBA中的某个子目录中运行查询时会出错。
这是我的数据库连接的代码
Sub dataquery()
Dim cntMyConnection As ADODB.Connection
Set cntMyConnection = New ADODB.Connection
Dim fld As ADODB.Field
Dim row As Long
Dim Col As Long
cntMyConnection.ConnectionString = "Driver={MySQL ODBC 8.0 ANSI Driver}; server=localhost; port=3306; database=assignment3; Uid=root; pwd=1qaz2wsx3edc!QAZ@WSX#EDC; option=3;"
cntMyConnection.Open
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
Dim src2 As String
src2 = **"select h.hunterID, h.year, h.hunted, h.harvested, m.sex, m.date_of_kill, m.gmu, m.horn_width, m.brow_tine_left, m.brow_tine_right, m.points_left, m.points_right from hunter as h inner join moose as m on m.hunterid = h.hunterid"**
rs.Open src2, cntMyConnection
If rs.EOF Then
MsgBox "No mathcing records found."
rs.Close
cntMyConnection.Close
Exit Sub
End If
row = 1
Col = 1
For Each fld In rs.Fields
Sheet2.Cells(row, Col).Value = fld.Name
Col = Col + 1
Next
rs.MoveNext
row = row + 1
Do While Not rs.EOF
Col = 1
For Each fld In rs.Fields
Sheet2.Cells(row, Col).Value = fld
Col = Col + 1
Next
row = row + 1
rs.MoveNext
Loop
rs.Close
cntMyConnection.Close
End Sub
我希望它返回联接的表并在excel中填充指定的单元格。