需要安装驱动,链接在底部
Option Explicit
'需要安装 MySQL 的 ODBC 驱动,官网上有,我的是 Connector ODBC 5.1
'先引用 Microsoft ActiveX Data Objects 6.0 Library 我的是 6.0,用最新的就行
Public conn As ADODB.Connection
Public rs As ADODB.Recordset
Public fld As ADODB.Field
Public Sub connOpen()
Set conn = New ADODB.Connection
conn.ConnectionString = "DRIVER={MySQL ODBC 5.1 Driver};" & _
"SERVER=localhost;" & "UID=用户名;PWD=密码;OPTION=3"
'注意ODBC驱动版本号,现在最新的 MySQL 5.4 + ODBC 5.1
'另外可以有 DATABASE=XX,或者在程序里使用 use database 语句
'OPTION是什么作用不知道,我这里可以不写
conn.Open
Set rs = New ADODB.Recordset
rs.CursorLocation = adUseClient '游标位置(数据集存在服务器内存还是客户端内存)
End Sub
Public Sub connClose()
rs.Close
conn.Close
End Sub
' 常用语句
' conn.Execute "drop database db_vb"
' conn.Execute "create database db_vb"
' conn.Execute "use db_vb"
' conn.Execute "create table test (id int primary key,name char(8) not null)"
' conn.Execute "insert into test value (1,'abc')"
' conn.Execute "insert into test value (2,'xyz')"
' 执行查询
' rs.Open "select * from test", conn
' 读取数据集
' Debug.Print rs.RecordCount '数据集数量
' rs.MoveFirst
' For Each fld In rs.Fields
' Debug.Print fld.Name, '列标题
' Next
' Debug.Print
' Do Until rs.EOF
' For Each fld In rs.Fields
' Debug.Print fld.Value,
' Next
' rs.MoveNext
' Debug.Print
' Loop
Views: 124