VBA错误:在“读取授权包”中丢失与MySQL服务器的连接,系统错误2

时间:2011-03-28 13:04:59

标签: mysql excel vba

这是我在宏执行约10分钟后得到的错误。宏基本上每五秒钟执行一次更新MySQL数据库的任务。

enter image description here

可能出现什么问题?

我的宏如下:

Public RunWhen As Double
Public Const cRunIntervalSeconds = 10 ' five seconds
Public Const cRunWhat = "UpdateMarketData"  ' the name of the procedure to run

Sub UpdateMarketData()

    Dim Cn As ADODB.Connection
    Dim Server_Name As String
    Dim Database_Name As String
    Dim User_ID As String
    Dim Password As String
    Dim SQLStr As String
    Dim rs As ADODB.Recordset
    Set rs = New ADODB.Recordset

    rad = 0



  TextStrang = TextStrang & "'"
  field2 = "cid"
  field1 = "bid"
  table1 = "MMbanner"

  For rowCursor = 3 To 4

    SQLStr = "UPDATE tbl_MarketData SET Mid = '" & Cells(rowCursor, 2) & "',Bid = '" & Cells(rowCursor, 5) & "',Offer = '" & Cells(rowCursor, 6) & "',DateEntered = '" & Format(DateTime.Now(), "yyyy-MM-dd hh:mm:ss") & "' WHERE IndexCode = '" & Cells(rowCursor, 1) & "'"
    Debug.Print SQLStr
    Set Cn = New ADODB.Connection

    Cn.Open "DRIVER={MySQL ODBC 3.51 Driver};SERVER=<Servername>; PORT=Portno; DATABASE=Databasename; USER=Username; PASSWORD=Password; OPTION=0;"

    Cn.Execute SQLStr
    rad = rad + 1
  Next
Set rs = Nothing
Cn.Close
Set Cn = Nothing

Call StartTimer

End Sub


Sub StartTimer()
    RunWhen = Now + TimeSerial(0, 0, cRunIntervalSeconds)
    Application.OnTime EarliestTime:=RunWhen, Procedure:=cRunWhat, _
        Schedule:=True
End Sub


Sub StopTimer()
    On Error Resume Next
    Application.OnTime EarliestTime:=RunWhen, Procedure:=cRunWhat, _
        Schedule:=False
End Sub

1 个答案:

答案 0 :(得分:3)

您的for循环通过Set Cn = New ADODB.Connection等创建两个单独的连接,但Cn.Close仅在for循环后调用一次。因此,创建的第一个连接未明确关闭,服务器仍将可能视为活动状态。最终你会用尽可用的连接,事情就会停滞不前。

不确定这是否是导致问题的原因,但绝对值得修复。我会在for循环之前创建并打开连接,但将Cn.Execute部分保留在循环体内