1. 程式人生 > >VBA連線mysql資料庫 程式碼示例

VBA連線mysql資料庫 程式碼示例

資料庫資訊的設定:將資料庫設定分為幾個模組。

①DB配置(config)

伺服器:servervip

資料庫資訊:database

使用者名稱:user

密碼:pqssword

②連線語句strConn

strConn = "Driver={MySQL ODBC 5.2 Unicode Driver};" & "Server=ip;" & "database=database;" & "USER=user;" & "PASSWORD=password;" & "OPTION=3;"

其中option指的是

'DB資訊

Public Db_sevip, Db_name, Db_user, Db_pwd As String '設定具體資料庫

Public db_connection As ADODB.Connection  '定義資料庫連線

Public Records As ADODB.Recordset                    '定義資料記錄集物件

Private Sub set_db_config() '資料庫的具體設定


Db_sevip = "ip"
Db_name = "database"
Db_user = "user"
Db_pwd = "password"
 Debug.Print Db_sevip
End Sub

Public Sub open_mysql_db()  '開啟sql資料來源  設定連線方式
Call set_db_config '呼叫資料來源的配置
Dim strConn As String
strConn = "Driver={MySQL ODBC 5.2 Unicode Driver};" & "Server=ip;" & "database=database;" & "USER=user;" & "PASSWORD=password;" & "OPTION=3;"


Debug.Print strConn
Set db_connection = New ADODB.Connection
db_connection.Open (strConn)
End Sub

Public Sub close_db()
If db_connection.State = 1 Then
db_connection.Close
      Set Conn = Nothing
End If
End Sub

Public Function read_sql_count(sql As String) As Integer
  Set Records = CreateObject("ADODB.recordset")


  Records.CursorType = adOpenStatic        '設定遊標型別,否則無法獲得行數
  Records.CursorLocation = adUseClient       '設定遊標屬性,否則無法獲得行數
  
  Records.Open sql, db_connection
  
  Debug.Print Records.RecordCount
  
  read_sql_count = Records.RecordCount
End Function


Public Sub   excute_Sql(sqlStr As String)
    Dim strConn As String, strSQL As String

    On Error GoTo Err
    
    db_connection.CommandTimeout = 10
    db_connection.Execute sqlStr
    
    Exit Sub
Err:
    MsgBox "sql 執行出錯" + Chr(10) + sqlStr

End Sub