Sub testMysqlOdbc()
'Dim conn As ADODB.Connection
'Dim rest As ADODB.Recordset
Set conn = CreateObject("ADODB.Connection")
Set rest = CreateObject("ADODB.Recordset")
'conn.ConnectionString = "DRIVER={MySQL ODBC 3.1 Unicode Driver};" & "SERVER=10.0.14.158;" & " DATABASE=hkoms;" & "UID=root;PWD=123 OPTION=3"
conn.ConnectionString = "DRIVER={MySQL ODBC 5.3 Unicode Driver};" & "SERVER=10.0.14.158;" & " DATABASE=hkoms;" & "UID=root; OPTION=3"
conn.Open
Dim sql As String
'sql = "select product_id,product_name from product p where p.product_name like '%a%'"
'sql = "select product_id,product_name from product p "
sql = "select * from sf_org"
Set rest = conn.Execute(sql)
Sheet1.Range("a1").CopyFromRecordset rest
conn.Close
Set conn = Nothing
Set rest = Nothing
'Dim conn As ADODB.Connection
'Dim rest As ADODB.Recordset
Set conn = CreateObject("ADODB.Connection")
Set rest = CreateObject("ADODB.Recordset")
'conn.ConnectionString = "DRIVER={MySQL ODBC 3.1 Unicode Driver};" & "SERVER=10.0.14.158;" & " DATABASE=hkoms;" & "UID=root;PWD=123 OPTION=3"
conn.ConnectionString = "DRIVER={MySQL ODBC 5.3 Unicode Driver};" & "SERVER=10.0.14.158;" & " DATABASE=hkoms;" & "UID=root; OPTION=3"
conn.Open
Dim sql As String
'sql = "select product_id,product_name from product p where p.product_name like '%a%'"
'sql = "select product_id,product_name from product p "
sql = "select * from sf_org"
Set rest = conn.Execute(sql)
Sheet1.Range("a1").CopyFromRecordset rest
conn.Close
Set conn = Nothing
Set rest = Nothing
End Sub
这里需要注意的是:
1, "DRIVER={MySQL ODBC 5.3 Unicode Driver};" 这一段,要根据自己电脑上安装的mysql odbc 版本不同而有区别,比如,我的电脑上安装的就是5.3版本。
2,创建数据库连接对象和记录集对象有两种方法:
'Dim conn As ADODB.Connection
'Dim rest As ADODB.Recordset
Set conn = CreateObject("ADODB.Connection")
Set rest = CreateObject("ADODB.Recordset")
我自己的选择是这样的:编码时使用前两种。使用或者分享时使用后两种。因为前两种有自动提示功能,后两种的优点是省去了繁琐的配置。