1. 程式人生 > >分享一個VBA連線mysql資料庫的方法

分享一個VBA連線mysql資料庫的方法

Dim strcn As String
Dim cn As New ADODB.Connection

'建構函式
Private Sub Class_Initialize()
strcn = "driver=mysql odbc 3.51 driver;" & _
"server=192.168.101.89;" & _
"database=mmtest;" & _
"uid=test;" & _
"pwd=test" & _
";Stmt=set names gb2312"
'";Stmt=set names gb2312" '連線字串

cn.Open strcn
cn.CursorLocation = adUseClient

End Sub

'解構函式
Private Sub Class_Terminate()
cn.Close
End Sub

'執行sql語句,返回行數
Public Function ExecCmd(ByVal strSql As String) As Long
Dim N As Long
cn.Execute strSql, N
ExecCmd = N
End Function

'執行sql語句,返回Recordset
Public Function ExecRecordset(ByVal strSql As String) As ADODB.Recordset
Dim rd As Recordset
Set rd = cn.Execute(strSql)

Set ExecRecordset = rd
End Function