与vb脚本的mysql连接(来自excel宏)

时间:2014-09-26 12:00:57

标签: mysql vb.net excel

我是vb脚本的新手。 我试图用这段代码连接mi本地mysql数据库:

Option Explicit
Private CN As ADODB.Connection

Function Connect(Server As String, Database As String) As Boolean

Set CN = New ADODB.Connection
On Error Resume Next

With CN

    .ConnectionString = "Driver={MySQL ODBC 5.3 Driver};Server=" & _
        Server & ";Database=" & Database & _
        ";Uid=user;Pwd=password;"
    .Open

End With

If CN.State = 0 Then
    Connect = False
Else
    Connect = True
End If 
End Function


Function Query(SQL As String)

Dim RS As ADODB.Recordset
Dim Field As ADODB.Field

Dim Col As Long 

Set RS = New ADODB.Recordset
RS.Open SQL, CN, adOpenStatic, adLockReadOnly, adCmdText

If RS.State Then
    Col = 1       
    For Each Field In RS.Fields
        Cells(1, Col) = Field.Name
        Inc Col
    Next Field        
    Cells(2, 1).CopyFromRecordset RS
    Set RS = Nothing
End If
End Function

Function Disconnect()    
CN.Close
End Function

Private Sub SQL_Click()

Dim SQL As String
Dim Connected As Boolean

SQL = "Select * from table1"

Connected = Connect("localhost", "table")

If Connected Then        
    Call Query(SQL)
    Call Disconnect
Else        
    MsgBox "Could Not Connect!"
End If

End Sub

始终显示无法连接。 ADODB库没问题,我的db参数适用于从mysql手动导入,驱动程序版本正确。我无法弄清楚发生了什么......

一些帮助?

感谢!!!

1 个答案:

答案 0 :(得分:0)

似乎连接字符串中的驱动程序名称错误。

尝试: " Driver = {MySQL ODBC 5.3 ANSI Driver}"