简体   繁体   中英

Connecting to Mysql db in Excel

So, I have to write a piece of code at my internship to link some excel worksheets with a MySQL DB and keep them updated, so far I have this but it keeps giving me errors. Do you see any mistakes? Thanks for reading.

The error I get is: runtime error -2147217900 automation error.

PS: I'm very new to 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

MySQL do not support "[" instead use " ` ".

Maybe is your connection string the problem.

ODBC Connection Style

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

OLEDB Connection Style

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM