此頁沒有內容條目
內容

GetRows 方法范例

該范例使用 GetRows 方法從 Recordset 中檢索指定數(shù)目的行,并將結果數(shù)據(jù)填充到數(shù)組。在兩種情況下 GetRows 方法返回的行將少于所需的數(shù)目:一種情況是因為達到了 EOF,另一種情況是因為 GetRows 試圖檢索已被其他用戶刪除的數(shù)據(jù)。僅當?shù)诙N情況發(fā)生時函數(shù)將返回 False。運行該過程需要使用 GetRowsOK 函數(shù)。

Public Sub GetRowsX()

   Dim rstEmployees As ADODB.Recordset

   Dim strCnn As String

   Dim strMessage As String

   Dim intRows As Integer

   Dim avarRecords As Variant

   Dim intRecord As Integer

   ' 使用雇員表中的姓名和受雇日期打開記錄集。

      strCnn = "Provider=sqloledb;" & _

      "Data Source=srv;Initial Catalog=pubs;User Id=sa;Password=; "

   Set rstEmployees = New ADODB.Recordset

   rstEmployees.Open "SELECT fName, lName, hire_date " & _

      "FROM Employee ORDER BY lName", strCnn, , , adCmdText

   Do While True

      ' 得到用戶輸入的行數(shù)。

      strMessage = "Enter number of rows to retrieve."

      intRows = Val(InputBox(strMessage))

      If intRows <= 0 Then Exit Do

      ' 如 GetRowsOK 成功則打印結果,請注意是否達到文件末端。

      If GetRowsOK(rstEmployees, intRows, _

            avarRecords) Then

         If intRows > UBound(avarRecords, 2) + 1 Then

            Debug.Print "(Not enough records in " & _

               "Recordset to retrieve " & intRows & _

               " rows.)"

         End If

         Debug.Print UBound(avarRecords, 2) + 1 & _

            " records found."

         ' 打印已檢索的數(shù)據(jù)。

         For intRecord = 0 To UBound(avarRecords, 2)

            Debug.Print "  " & _

               avarRecords(0, intRecord) & " " & _

               avarRecords(1, intRecord) & ", " & _

               avarRecords(2, intRecord)

         Next intRecord

      Else

         ' 假定 GetRows 錯誤源于其他用戶對數(shù)據(jù)的更改,

         ' 使用 Requery 刷新 Recordset 并重新開始。

         If MsgBox("GetRows failed--retry?", _

               vbYesNo) = vbYes Then

            rstEmployees.Requery

         Else

            Debug.Print "GetRows failed!"

            Exit Do

         End If

      End If

      ' 由于使用 GetRows 使當前記錄指針指向訪問過的最后一個記錄,

      ' 所以,在循環(huán)回到另一次搜索前將記錄指針移回 Recordset 的開始。

      rstEmployees.MoveFirst

   Loop

   rstEmployees.Close

End Sub

Public Function GetRowsOK(rstTemp As ADODB.Recordset, _

   intNumber As Integer, avarData As Variant) As Boolean

   ' 將 GetRows 方法的結果保存在數(shù)組中。

   avarData = rstTemp.GetRows(intNumber)

   ' 僅當返回的行數(shù)少于所需的行數(shù)而非由于到達了 Recordset 末端時才返回 False。

   If intNumber > UBound(avarData, 2) + 1 And _

         Not rstTemp.EOF Then

      GetRowsOK = False

   Else

      GetRowsOK = True

   End If

End Function