在Excel中连接到Mysql数据库

时间:2012-10-05 10:50:22

标签: mysql excel vba

所以,我必须在我的实习中写一段代码,将一些excel工作表与MySQL数据库链接起来并保持更新,到目前为止我已经有了这个,但它一直给我错误。你看到有什么错误吗? 谢谢你的阅读。

我得到的错误是:运行时错误-2147217900自动化错误。

PS:我对VBA很新。

Dim server_name As String
Dim database_name As String
Dim user As String
Dim Password As String
Dim rs As adodb.Recordset
Dim naam As String
Dim oConn As adodb.Connection


Public Sub getSerieNummer()

Dim result As String
Dim b As Long
Dim strSQL As String

naam = Range("C1").Value

server_name = "servername"
database_name = "dbname"
user_id = "idname"
Password = "password"

Set oConn = New adodb.Connection
oConn.Open "SERVER=" & server_name _
& ";PORT=3306" _
& ";DATABASE=" & database_name _
& ";UID=" & user_id _
& ";PWD=" & Password & _
";DSN=name_in_odbc;"

strSQL = "SELECT [serial_number] FROM view_aix WHERE [name] ='" & naam & "';"
Set rs = oConn.Execute(strSQL)

b = 0
With rs
    Do Until .EOF
    b = b + 1
    result = !serial_number
    rs.MoveNext
    Loop
End With
    oConn.Close
    rs.Close
Set rs.ActiveConnection = Nothing
Set oConn = Nothing
Range("C2").Value = result

End Sub

1 个答案:

答案 0 :(得分:0)

MySQL不支持“[”而是使用“`”。

可能是你的连接字符串出了问题。

ODBC连接样式

Driver={mySQL};Server=localhost;Option=16834;Database=myDataBase;

OLEDB连接样式

Provider=MySQLProv;Data Source=mydb;User Id=myUsername;Password=myPassword;