VBALinkMysql/DatabaseConn.vba

37 lines
1.0 KiB
Plaintext

'----关闭数据库连接,释放资源
Public Sub closeConn()
On Error Resume Next
If conn Is Nothing Then Exit Sub
conn.Close
Set conn = Nothing
End Sub
'----连接数据库,创建结果集对象
Public Sub AutoRun()
Call closeConn
On Error Resume Next
Dim strDBinf As String
Application.StatusBar = "正在连接数据库……"
If conn Is Nothing Then
Set conn = New ADODB.Connection
Set RES = CreateObject("ADODB.Recordset")
strDBinf = "DSN=mysqlinklexcel32" '标准语句
Call conn.Open(strDBinf)
If VBA.Err.Number <> 0 Then
strDBinf = "DSN=mysqlinklexcel64" '标准语句
VBA.MsgBox "32位DSN连接失败,尝试使用mysqllinkexcel6连接!"
Call conn.Open(strDBinf)
End If
If VBA.Err.Number > 1 Then
VBA.MsgBox "连接异常,请检查DB环境!"
Set conn = Nothing
End If
Application.StatusBar = "数据库连接成功"
End If
End Sub