这是我在宏执行约10分钟后得到的错误。宏基本上每五秒钟执行一次更新MySQL数据库的任务。
可能出现什么问题?
我的宏如下:
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
答案 0 :(得分:3)
您的for
循环通过Set Cn = New ADODB.Connection
等创建两个单独的连接,但Cn.Close
仅在for
循环后调用一次。因此,创建的第一个连接未明确关闭,服务器仍将可能视为活动状态。最终你会用尽可用的连接,事情就会停滞不前。
不确定这是否是导致问题的原因,但绝对值得修复。我会在for
循环之前创建并打开连接,但将Cn.Execute
部分保留在循环体内