VBA如何在Excel中连接到MySQL数据库?

VBA如何在Excel中连接到MySQL数据库?

问题描述:

Dim oConn As ADODB.Connection
Private Sub ConnectDB()
Set oConn = New ADODB.Connection
Dim str As String
str = "DRIVER={MySQL ODBC 5.2.2 Driver};" & _
                                            "SERVER=sql100.xtreemhost.com;" & _
                                            "PORT=3306" & _
                                            "DATABASE=xth_9595110_MyNotes;" & _
                                            "UID=xth_9595110;" & _
                                            "PWD=myPassword;" & _
                                            "Option=3"
''' error '''
oConn.Open str
End Sub

Private Sub InsertData()
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
ConnectDB
sql = "SELECT * FROM ComputingNotesTable"
rs.Open sql, oConn, adOpenDynamic, adLockOptimistic
Do Until rs.EOF
    Range("A1").Select
    ActiveCell = rs.Fields("Headings")
    rs.MoveNext
Loop
rs.Close
oConn.Close
Set oConn = Nothing
Set rs = Nothing
End Sub

在PHP中做类似的事情,我可以成功登录到MySQL服务器。
我已经安装了ODBC连接器。
但是在上述VBA代码中,我失败了。
发生错误。 (见代码存在错误)

Doing the similar things in PHP, I could successfully log in to the MySQL server. I have installed the ODBC connector. But in the above VBA codes, I failed. An error turns up. (see the codes where the error exists)

$connect = mysql_connect("sql100.xtreemhost.com","xth_9595110","myPassword") or die(mysql_error());

mysql_select_db("myTable",$connect);


Ranjit的代码导致与锡报告相同的错误消息,但在使用正在运行的ODBC驱动程序更新Cn.open后工作。检查ODBC数据源管理器中的驱动程序选项卡。 Mine表示MySQL ODBC 5.3 Unicode驱动程序,所以我相应更新。

Ranjit's code caused the same error message as reported by Tin, but worked after updating Cn.open with the ODBC driver I'm running. Check the Drivers tab in the ODBC Data Source Administrator. Mine said "MySQL ODBC 5.3 Unicode Driver" so I updated accordingly.