该范例使用 Cancel 方法,取消连接繁忙时正在连接对象上执行的命令。
Public Sub CancelX()
Dim cnn1 As ADODB.Connection
Dim strCnn As String
Dim strCmdChange As String
Dim strCmdRestore As String
Dim booChanged As Boolean
' 打开连接。
Set cnn1 = New ADODB.Connection
strCnn = "Provider=sqloledb;" & _
"Data Source=srv;Initial Catalog=pubs;User Id=sa;Password=; "
cnn1.Open strCnn
' 定义命令字符串。
strCmdChange = "UPDATE titles SET type = 'self_help' " & _
"WHERE type = 'psychology'"
strCmdRestore = "UPDATE titles SET type = 'psychology' " & _
"WHERE type = 'self_help'"
' 开始事务,然后异步执行命令。
cnn1.BeginTrans
cnn1.Execute strCmdChange, , adAsyncExecute
' 做一会其他的事情(可以将其更改)。
For i = 1 To 10
i = i + i
Debug.Print i
Next i
' 如果命令没有完成,取消执行并回卷事务。否则提交事务。
If CBool(cnn1.State And adStateExecuting) Then
cnn1.Cancel
cnn1.RollbackTrans
booChanged = False
MsgBox "Update canceled."
Else
cnn1.CommitTrans
booChanged = True
MsgBox "Update complete."
End If
' 如果已经更改,则恢复数据,因为这只是演示。
If booChanged Then
cnn1.Execute strCmdRestore
MsgBox "Data restored."
End If
cnn1.Close
End Sub