Excel插件连接到MySQL服务器

gpfsuwkq  于 2024-01-05  发布在  Mysql
关注(0)|答案(1)|浏览(175)

我在db4free.net上建立了一个测试数据库,并上传了一份northwind训练数据库的副本,看看我是否可以将一些信息拉到excel工作簿中,并继续得到通用的unspecified/automation错误。
我在参考资料中包括了“Microsoft ActiveX Data Objects 2.8 library”,甚至尝试了6.1。
在任何人对我发脾气之前,包括用户名和密码;这个测试数据库中唯一存在的是一个训练数据集。我在那里存储了零个个人信息。
下面是我的代码:

  1. Sub sqlTest()
  2. 'Declare some strings to hold the connection string and the SQL statement
  3. Dim cnStr As String
  4. Dim sqlStr As String
  5. 'Define a connection and a recordset to hold extracted information
  6. Dim oConn As ADODB.Connection
  7. Dim rcSet As New ADODB.Recordset
  8. Set oConn = New ADODB.Connection
  9. Set rcSet = CreateObject("ADODB.Recordset")
  10. 'connection string to connect to db4free.net
  11. cnStr = "Driver={MySQL ODBC 8.0 Unicode Driver};SERVER=85.10.205.173;DATABASE=resumedemo;PORT=3306;UID=jwaycaster;PWD=resumedemo123;"
  12. 'Test SQL query
  13. sqlStr = "SELECT * FROM `Employees`"
  14. 'This is where it crashes
  15. oConn.Open cnStr
  16. oConn.CommandTimeout = 900
  17. rcSet.Open sqlStr, oConn
  18. Sheets(1).Range("A1").CopyFromRecordset rcSet
  19. rcSet.Close
  20. oConn.Close
  21. End Sub

字符串
我已经搜索了几个相关的主题,似乎找不到答案。希望我错过了一些简单的东西。
为后代编辑:在阅读回复后,我意识到这台计算机上没有安装驱动程序(我正在拜访亲戚,不敢相信我忘记检查了)。在安装驱动程序并更新我的引用后,我的代码执行得很好,但我建议使用CDP 1802。

6ioyuze2

6ioyuze21#

有时候自己处理错误会很有用。

  1. Microsoft ActiveX数据对象6.1库
  2. Microsoft ActiveX数据对象RecordSet 6.0库
  1. Option Explicit
  2. Sub sqlTest()
  3. ' credentials
  4. Const SERVER = "85.10.205.173"
  5. Const DB = "resumedemo"
  6. Const UID = "jwaycaster"
  7. Const PWD = "resumedemo123"
  8. 'Define a connection and a recordset to hold extracted information
  9. Dim oConn As ADODB.Connection, rcSet As ADODB.Recordset
  10. Dim cnStr As String, n As Long, msg As String, e
  11. 'connection string to connect to db4free.net
  12. cnStr = "Driver={MySQL ODBC 8.0 Unicode Driver};SERVER=" & SERVER & _
  13. ";PORT=3306;DATABASE=" & DB & _
  14. ";UID=" & UID & ";PWD=" & PWD & ";"
  15. 'Test SQL query
  16. Const SQL = "SELECT * FROM `Employees`"
  17. ' connect
  18. Set oConn = New ADODB.Connection
  19. 'oConn.CommandTimeout = 900
  20. On Error Resume Next
  21. oConn.Open cnStr
  22. If oConn.Errors.Count > 0 Then
  23. For Each e In oConn.Errors
  24. msg = msg & vbLf & e.Description
  25. Next
  26. MsgBox msg, vbExclamation, "ERROR - Connection Failed"
  27. Exit Sub
  28. Else
  29. MsgBox "Connected to database " & oConn.DefaultDatabase, vbInformation, "Success"
  30. End If
  31. ' run query
  32. Set rcSet = oConn.Execute(SQL, n)
  33. If oConn.Errors.Count > 0 Then
  34. msg = ""
  35. For Each e In oConn.Errors
  36. msg = msg & vbLf & e.Description
  37. Next
  38. MsgBox msg, vbExclamation, "ERROR - Execute Failed"
  39. Else
  40. Sheets(1).Range("A1").CopyFromRecordset rcSet
  41. MsgBox SQL & " returned " & n & " records", vbInformation
  42. End If
  43. On Error GoTo 0
  44. oConn.Close
  45. End Sub

字符串

展开查看全部

相关问题