Option Explicit
Function action
Dim adoConn '定义ADO连接对象
Dim ConnectionStr '定义数据库连接字符串
Dim sqlStr
'获取连接数据库字符串
ConnectionStr="Provider=MSDASQL.1;Persist Security Info=True;Extended Properties='Driver=MySQL ODBC 5.3 ANSI Driver;SERVER=localhost;UID=root;PWD=root;DATABASE=test;PORT=3306'"
Set adoConn = CreateObject("ADODB.Connection")
'利用数据库连接字符串打开数据库
On Error Resume Next
adoConn.Open ConnectionStr
'查看是否连接成功,成功状态值为1
'msgbox adoConn.state
If adoConn.State = 0 Then
Msgbox "连接数据库失败!"
else
Msgbox "连接数据库成功!"
End If
'获取数据库查询语句
sqlStr = "select * from utest where id=1 "
'执行sql语句并返回对应的结果集
Set adoRst = adoConn.Execute(sqlStr)
'获得结果集中年龄字段的值
MsgBox adoRst.Fields.Item("ub").Value
'关闭数据库
adoConn.Close
'释放数据库对象
Set adoConn = Nothing
Function action
Dim adoConn '定义ADO连接对象
Dim ConnectionStr '定义数据库连接字符串
Dim sqlStr
'获取连接数据库字符串
ConnectionStr="Provider=MSDASQL.1;Persist Security Info=True;Extended Properties='Driver=MySQL ODBC 5.3 ANSI Driver;SERVER=localhost;UID=root;PWD=root;DATABASE=test;PORT=3306'"
Set adoConn = CreateObject("ADODB.Connection")
'利用数据库连接字符串打开数据库
On Error Resume Next
adoConn.Open ConnectionStr
'查看是否连接成功,成功状态值为1
'msgbox adoConn.state
If adoConn.State = 0 Then
Msgbox "连接数据库失败!"
else
Msgbox "连接数据库成功!"
End If
'获取数据库查询语句
sqlStr = "select * from utest where id=1 "
'执行sql语句并返回对应的结果集
Set adoRst = adoConn.Execute(sqlStr)
'获得结果集中年龄字段的值
MsgBox adoRst.Fields.Item("ub").Value
'关闭数据库
adoConn.Close
'释放数据库对象
Set adoConn = Nothing
End Function
为啥一直包数据库连接失败?
本文通过一个具体的示例演示了如何使用VBA连接MySQL数据库,并展示了如何执行SQL查询语句来从数据库中检索数据。文章详细解释了创建ADO连接对象、设置数据库连接字符串的过程,并给出了错误处理的方法。
7622

被折叠的 条评论
为什么被折叠?



