我很感激帮助解决从Excel访问MySQL数据库的问题。
我在phpmyadmin中创建了数据库。我还能够通过CSV文件手动将数据导入phhpmyadmin的SQL数据库。
所以,我确信我拥有正确的数据库IP地址,用户名和密码。
我还阅读了有关如何配置从Windows到SQL的ODBC连接的各种帖子,我想我已按照正确的说明进行操作。
但是,我似乎无法从VBA获得代码。我不断收到各种错误。
这是我一直在使用的代码,减去实际的数据库名称和用户ID。
Private Sub cmdInsertData_Click()
Dim oConn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim Pwd As String
Dim SQLStr As String
Dim Svr_Nm As String
Dim UID As String
Dim Dbs_Nm As String
' Input Parameters
Pwd = "mypassword"
UID = "myuser"
srvr_nm = "xxx.xxx.xx.xx:yyyy"
Dbs_Nm = "myname"
Set rs = New ADODB.Recordset
Set oConn = New ADODB.Connection
SQLStr = "DRIVER={MySQL ODBC 5.3 ANSI Driver};"
SQLStr = SQLStr & "SERVER=" & srvr_nm & ";DATABASE=" & Dbs_Nm & ";USER=" & UID & ";PASSWORD=" & Pwd & ";Option=3"
oConn.Open SQLStr
MsgBox "Connected to " & Dbs_Nm & " via " & srvr_nm
End Sub
我已按如下方式重置代码。错误消息由“oConn.Open SQLStr”行生成。产生的错误是
运行时错误'-2147467259(80004005)': [MySQL] [ODBC 5.3(a)驱动程序]未知MySQL服务器主机'209.159.152.202:2083'(0)
新守则:
Private Sub CheckConnection()
Dim oConn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim Pwd As String
Dim SQLStr As String
Dim Svr_Nm As String
Dim Usr_ID As String
Dim Dbs_Nm As String
' Input Parameters
Pwd = "mypassword"
Usr_ID = "myID"
srvr_nm = "209.159.152.202:2083"
Dbs_Nm = "mydatabase"
Set rs = New ADODB.Recordset
Set oConn = New ADODB.Connection
SQLStr = "DRIVER={MySQL ODBC 5.3 ANSI Driver};"
SQLStr = SQLStr & "SERVER=" & srvr_nm & ";DATABASE=" & Dbs_Nm & ";USER=" & Usr_ID & ";PASSWORD=" & Pwd & ";Option=3"
oConn.Open SQLStr
MsgBox "Connected to " & Dbs_Nm & " via " & srvr_nm
End Sub
感谢有关将Port =添加为单独变量的建议。我已经尝试过了(参见新代码)但它仍然无法正常工作。
Private Sub CheckConnection()
Dim oConn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim Pwd As String
Dim SQLStr As String
Dim Svr_Nm As String
Dim Usr_ID As String
Dim Dbs_Nm As String
Dim Port_Nm As String
' Input Parameters
Pwd = "mypassword"
Usr_ID = "myID"
Svr_Nm = "209.159.152.202"
Dbs_Nm = "mydatabase"
Port_Nm = "2083"
Set rs = New ADODB.Recordset
Set oConn = New ADODB.Connection
SQLStr = "DRIVER={MySQL ODBC 5.3 ANSI Driver};"
SQLStr = SQLStr & "Server=" & Svr_Nm & ";Port=" & Port_Nm & ";Database=" & Dbs_Nm & ";User=" & Usr_ID & ";Password=" & Pwd & ";Option=3"
oConn.Open SQLStr
MsgBox "Connected to: " & Dbs_Nm & " via " & Svr_Nm
End Sub
我仍然在同一个地方收到相同的错误消息。