此頁(yè)沒有內(nèi)容條目
內(nèi)容

Cancel 方法范例

該范例使用 Cancel 方法,取消連接繁忙時(shí)正在連接對(duì)象上執(zhí)行的命令。

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'"

   ' 開始事務(wù),然后異步執(zhí)行命令。

   cnn1.BeginTrans

   cnn1.Execute strCmdChange, , adAsyncExecute

   ' 做一會(huì)其他的事情(可以將其更改)。

      For i = 1 To 10

         i = i + i

         Debug.Print i

      Next i

   ' 如果命令沒有完成,取消執(zhí)行并回卷事務(wù)。否則提交事務(wù)。

   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

   ' 如果已經(jīng)更改,則恢復(fù)數(shù)據(jù),因?yàn)檫@只是演示。

   If booChanged Then

      cnn1.Execute strCmdRestore

      MsgBox "Data restored."

   End If

   cnn1.Close

End Sub