Cancel 方法范例 该范例使用 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'"
' 做一会其他的事情(可以将其更改)。 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
早试过了,提示是在异步连接时操作不能被执行如果用Cancel方法的话是等到超时了才出来的
该范例使用 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
你那范例我早用过ADO手册里一模一样挖出来的。。你自己也可以试下,貌似真的在open里面Cancel 方法真的没作用http://www.sunshinebean.com/video/ado.htm我就是想达到点了连接后马上能手动取消连接的我想这个应该是异步实现的吧
4楼那个效果应该可以实现,你可利用异步的特点,试试在cn.cancel前启动一个timer,给一个小小的延时即可,销毁cn,控制按键的代码写在timer相关事件中,cn.cancel之下不写代码....