繁体   English   中英

Excel 2016 vba ADODB与MySQL

[英]Excel 2016 vba ADODB with MySQL

嗨,我需要从excel连接到MySQL数据库,我发现了以下示例:

http://forums.mysql.com/read.php?10,100302

根据我的要求修改它,但是在运行时它什么也没做,也没有给我错误。

Option Explicit
Option Base 1

Sub excelmysql()
' VBA to perform various actions on MySQL tables using VBA
' Majority of the original code adapted from Carlmack http://www.ozgrid.com/forum/showthread.php?t=46893

' PLEASE DO THE FOLLOWING BEFORE EXECUTING CODE:
' 1)In VBE you need to go Tools/References and check Microsoft Active X Data Objects 2.x library
' 2)Install MySQL ODBC 3.51 Driver. See dev.mysql.com/downloads/connector/odbc/3.51.html or google "MySQL ODBC 3.51 Driver"

'-------------------------------------------------------------------------
' Connection variables
Dim conn As New ADODB.Connection
Dim server_name As String
Dim database_name As String
Dim user_id As String
Dim password As String

' Table action variables
Dim i As Long ' counter
Dim sqlstr As String ' SQL to perform various actions
Dim table1 As String, table2 As String
Dim field1 As String, field2 As String
Dim rs As ADODB.Recordset
Dim vtype As Variant

'----------------------------------------------------------------------
' Establish connection to the database
server_name = "127.0.0.1" ' Enter your server name here - if running from a local computer use 127.0.0.1
database_name = "pruebas" ' Enter your database name here
user_id = "prueba" ' enter your user ID here
password = "12345678" ' Enter your password here

Set conn = New ADODB.Connection
conn.Open "DRIVER={MySQL ODBC 3.51 Driver}" _
& ";SERVER=" & server_name _
& ";DATABASE=" & database_name _
& ";UID=" & user_id _
& ";PWD=" & password _
& ";OPTION=16427" ' Option 16427 = Convert LongLong to Int: This just helps makes sure that large numeric results get properly interpreted

'---------------------------------------------
' Extract MySQL table data to first worksheet in the workbook
GoTo skipextract
Set rs = New ADODB.Recordset
sqlstr = "select dato1 from datos where IdDato=1" ' extracts all data
rs.Open sqlstr, conn, adOpenStatic
With Worksheets("Hoja1").Cells("A1") ' Enter your sheet name and range here
.ClearContents
.CopyFromRecordset rs
End With
skipextract:

'-----------------------------------------------------------------------
' Close connections
On Error Resume Next
rs.Close
Set rs = Nothing
conn.Close
Set conn = Nothing
On Error GoTo 0
End Sub

非常感谢您的关注和时间。

最好的祝福。

这行:

GoTo skipextract

绕过您实际查询数据库的位置。 它会将应用程序带到您关闭连接并删除变量的行。 我想这是复制造成的错误,应该是

On Error GoTo skipextract

这样它可以捕获任何连接错误并关闭连接。 但是,如果没有错误出现,它将按您的期望进行查询。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM