请问如何在ADO中用异步的方式打开一个RecordSet? 因为我有一个SQL语句,用
RecordSet.Open "..." 的方式打开,时间会很长,我想让用户在OPEN 的时候能够取消OPEN 操作,该如何做?我用adExecuteAsync参数为什么不行?请专家们多多指教,谢谢!
回答:
首先,常量应是adAsyncExecute而不是adExecuteAsync。在ADO中,Connection/Command/RecordSet对象均允许异步操作,记录集对象通过adAsyncExecute参数来实现。如果想要在异步执行过程中取消它,方法有以下几种。
新建一个窗体,在窗体中放置两个按钮Command1,Command2,当用户按下Command1按钮时,异步打开记录集,当用户按下Command2,取消异步操作。
其中blnStop,Recordset1,Connection1均为模块级变量。
一、使用记录集的Cancel方法和State属性。例子代码:
Dim recordset1 As New Recordset
Dim Connection1 As New Connection
Dim blnStop As Boolean
Private Sub Command1_Click()
Connection1.ConnectionString = "Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;Initial Catalog=pubs;Data Source=(local)"
Connection1.Open
recordset1.Open "select * from authors", Connection1, adOpenStatic, adLockReadOnly, adAsyncExecute
Do
If recordset1.State And adStateOpen Then
MsgBox "异步执行结束!"
Exit Do
Else
If blnStop Then
If CBool(recordset1.State And adStateExecuting) Then
recordset1.Cancel
MsgBox "用户取消执行!"
End If
End If
End If
DoEvents
Loop
End Sub
Private Sub Command2_Click()
blnStop = Not blnStop
End Sub
Private Sub Form_Load()
blnStop = False
End Sub