Filter 和 RecordCount 属性示例 (VB)
此示例在 Pubs 数据库的 Publishers 表上打开一个 Recordset。 其随后使用 Filter 属性来限制特定国家/地区的发布服务器可见的记录数。 RecordCount 属性用于显示筛选记录集与未筛选记录集之间的差异。
'BeginFilterVB
'To integrate this code
'replace the data source and initial catalog values
'in the connection string
Public Sub Main()
On Error GoTo ErrorHandler
' recordset variables
Dim rstPublishers As ADODB.Recordset
Dim Cnxn As ADODB.Connection
Dim strCnxn As String
Dim SQLPublishers As String
' criteria variables
Dim intPublisherCount As Integer
Dim strCountry As String
Dim strMessage As String
' open connection
Set Cnxn = New ADODB.Connection
strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Cnxn.Open strCnxn
' open recordset with data from Publishers table
Set rstPublishers = New ADODB.Recordset
SQLPublishers = "publishers"
rstPublishers.Open SQLPublishers, strCnxn, adOpenStatic, , adCmdTable
intPublisherCount = rstPublishers.RecordCount
' get user input
strCountry = Trim(InputBox("Enter a country to filter on (e.g. USA):"))
If strCountry <> "" Then
' open a filtered Recordset object
rstPublishers.Filter = "Country ='" & strCountry & "'"
If rstPublishers.RecordCount = 0 Then
MsgBox "No publishers from that country."
Else
' print number of records for the original recordset
' and the filtered recordset
strMessage = "Orders in original recordset: " & _
vbCr & intPublisherCount & vbCr & _
"Orders in filtered recordset (Country = '" & _
strCountry & "'): " & vbCr & _
rstPublishers.RecordCount
MsgBox strMessage
End If
End If
' clean up
rstPublishers.Close
Cnxn.Close
Set rstPublishers = Nothing
Set Cnxn = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not rstPublishers Is Nothing Then
If rstPublishers.State = adStateOpen Then rstPublishers.Close
End If
Set rstPublishers = Nothing
If Not Cnxn Is Nothing Then
If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing
If Err <> 0 Then
MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndFilterVB
注意
如果知道要选择的数据,通常使用 SQL 语句打开 Recordset 会更高效。 此示例演示如何仅创建 Recordset,并从特定国家/地区获取记录。
Attribute VB_Name = "Filter"
另请参阅
反馈
https://aka.ms/ContentUserFeedback。
即将发布:在整个 2024 年,我们将逐步淘汰作为内容反馈机制的“GitHub 问题”,并将其取代为新的反馈系统。 有关详细信息,请参阅:提交和查看相关反馈