我写了一个用于将数据插入到mysql-DB中的vba代码,并节省了我想要执行多次"插入"只有一个与数据库的连接,但我担心插入命令可能出现错误,所以如果出现错误,我想一次执行一次查询。
这使得可以无错误地执行命令,但是,如果出现错误,它将再次出现,我将需要处理它。
为了做到这一点,我想到了下面的代码,但是,寻找类似的东西,我没有找到任何东西......也许这是一个坏主意?有更好的方法吗?
这是我的想法:
For i = 1 To 100
'...do something
'First error handling activation
On Error GoTo ErrHandle1
'Reset SQL String
SQLStr = ""
'Loop for making SQL string for multiple INSERT
For ii = 1 To 50
'...example instructions:
SQLStr = SQLStr & "INSERT INTO myTab (myField) VALUES ('" & ii / i & "'); "
Next ii
'Execute all insert at one time
rs.Open SQLStr, Cn, adOpenStatic
GoNext:
On Error GoTo 0
Next i
Exit Sub
'primary error handling
ErrHandle1:
'No instrutions here
'I use resume only to reset error
Resume Handle1
Handle1:
'I try again INSERT loop with a connection to DB for every query
'Second error handling activation
On Error GoTo ErrHandle2
For ii = 1 To 50
'String for only one INSERT
SQLStr = "INSERT INTO myTab (myField) VALUES ('" & ii / i & "'); "
'Single query execution
rs.Open SQLStr, Cn, adOpenStatic
Next ii
'Back to base code
GoTo GoNext
'secondary error handling
ErrHandle2:
MsgBox Err & " - " & Error(Err)
Resume Next
答案 0 :(得分:1)
我建议在错误级别放置错误处理例程(正常过程中使用 If False 分隔符)。如果出现基本错误,请避免 GoTo 0 ,它只会耗尽资源。
On Error GoTo ErrHandleri
For i = 1 To 100
'...do something
For ii =1 To 50
On Error GoTo ErrHandlerii
'do other thing
If False Then
Errhandlerii:
'do error handling stuff
End If
Next ii
If False Then
ErrHandleri:
'code, e.g. paint the whole line blue
End If
Next i