Recordset — это объект, который используется для выполнения операций с записями. Семейство Recordsets содержит все открытые объекты Recordset в открытой базе данных. При закрытии объекта Recordset он удаляется из памяти и из семейства Recordsets. Объекты Database, TableDef и QueryDef включает метод OpenRecordset.
Recordset можно открыть, указав в методе OpenRecordset объекта Database название соответствующей таблицы или воспользовавшись методом OpenRecordset объекта TableDef:
Dim dbsNorthwind As Database
Dim rstEmployees As Recordset
Set dbsNorthwind = OpenDatabase("Northwind.mdb")
Set rstEmployees = dbsNorthwind.OpenRecordset( "Employees", dbOpenDynaset)
После открытия объекта Recordset необходимо определить, какие записи доступны. Если в Recordset нет ни одной записи, то его свойства BOF (Beginning Of File — начало файла) и EOF (End Of File — конец файла) установлены в True. Если EOF установлено в False, то Recordset имеет хотя бы одну запись. Если записи существуют, то при открытии Recordset будет выполнено позиционирование на первой записи.
Используя метод Move , можно построить цикл, обращающийся к каждой следующей записи в объекте Recordset. Метод MoveLast используется для позиционирования к последней записи Recordset. Для перемещения к предыдущей записи используется метод MovePrevious , пока свойство BOF не будет установлено в True. Метод MoveFirst может быть использован для позиционирования к первой записи.
Метод Edit информирует Jet о том, что в текущей записи происходят изменения. При использовании метода Update сделанные изменения вносятся в таблицу.
Для добавления записей используйте метод AddNew . Этот метод применяется в комплексе с методом Edit при добавлении новых записей. Как и в случае с методом Edit, записи будут присоединены к таблице после применения метода Update.
Для удаления текущей записи используйте метод Delete .
После того как обработка объекта Recordset будет завершена, закройте его, воспользовавшись методом Close . Этот метод удаляет объект Recordset из семейства Recordsets и делает объект Recordset недействительным.
Некоторые методы:
AddNew |
Creates a new record for an updatable Recordset object. |
With rstTemp
.AddNew
!FirstName = strFirst
!LastName = strLast
.Update
.Bookmark = .LastModified
End With |
CancelUpdate |
Cancels any pending updates for a Recordset object. |
With rstEmployees
.CancelUpdate
MsgBox "Record not modified."
End With |
Close |
Closes an open DAO object. |
dbsNorthwind.Close |
Delete |
Recordset objects deletes the current record in an updatable Recordset object. |
With tdfTemp
If strCommand = "APPEND" Then
.Fields.Append .CreateField(strName, _
varType, varSize)
Else
If strCommand = "DELETE" Then .Fields.Delete strName
End If
End With |
Edit |
Copies the current record from an updatable Recordset object to the copy buffer for subsequent editing. |
With rstTemp
.Edit
!FirstName = strFirst
!LastName = strLast
.Update
.Bookmark = .LastModified
End With |
FindFirst |
Locates the first, last, next, or previous record in a dynaset- or snapshot-type Recordset object that satisfies the specified criteria and makes that record the current record. If recordset contains more than one record that satisfies the criteria, FindFirst locates the first occurrence, FindNext locates the next occurrence, and so on. |
strCountry = _
Trim(InputBox("Enter country for search."))
If strCountry = "" Then Exit Do
With rstCustomers
.MoveLast
.FindFirst strCountry
If .NoMatch Then
MsgBox "No records found with " & _
strCountry & "."
Exit Do
End If |
FindLast |
FindNext |
FindPrevious |
Move |
Moves the position of the current record in a Recordset object. |
With rstOutput
Do While Not .EOF
Debug.Print , .Fields(0), .Fields(1)
.MoveNext
Loop
End With |
MoveFirst |
MoveLast |
MoveNext |
MovePrevious |
OpenRecordset |
Creates a new Recordset object and appends it to the Recordsets collection. |
Dim wrkODBC As Workspace
Dim conPubs As Connection
Set wrkODBC = CreateWorkspace("", "admin", "", dbUseODBC)
Set conPubs = wrkODBC.OpenConnection("", , , _
"ODBC;DATABASE=pubs;UID=sa;PWD=;DSN=Publishers") |
Update |
Saves the contents of the copy buffer to an updatable Recordset object. |
Некоторые свойства:
AbsolutePosition |
Sets or returns the relative record number of a Recordset object's current record. |
strMessage = "Employee: " & !LastName & vbCr & _
"(record " & (.AbsolutePosition + 1) & _
" of " & .RecordCount & ")" |
Bookmark |
Sets or returns a bookmark that uniquely identifies the current record in a Recordset object. |
If IsEmpty(varBookmark) Then
MsgBox "No Bookmark set!"
Else
.Bookmark = varBookmark
End If |
Bookmarkable |
Returns a value that indicates whether a Recordset object supports bookmarks, which you can set by using the Bookmark property. |
EditMode |
Returns a value that indicates the state of editing for the current record. |
LastModified |
Returns a bookmark indicating the most recently added or changed record. |
.Bookmark = .LastModified |
Name |
Sets or returns a user-defined name for a DAO object. For an object not appended to a collection, this property is read/write. |
Set dbsNorthwind = OpenDatabase("Northwind.mdb")
With dbsNorthwind
Set qdfNew = .CreateQueryDef()
qdfNew.Name = "NewQueryDef"
qdfNew.SQL = "SELECT * FROM Employees"
.QueryDefs.Append qdfNew
Debug.Print "Names of queries in " & .Name
.QueryDefs.Delete qdfNew.Name
.Close
End With |
NoMatch |
Indicates whether a particular record was found by using the Seek method or one of the Find methods |
RecordCount |
|
|
RecordStatus |
Returns a value indicating the update status of the current record if it is part of a batch update |
dbRecordUnmodified, dbRecordModified, dbRecordNew, dbRecordDeleted, dbRecordDBDeleted |
Sort |
Sets or returns the sort order for records in a Recordset object |
.Sort = "LastName, FirstName" |
Type |
Sets or returns a value that indicates the operational type or data type of an object. |
dbBigInt, dbBinary, dbBoolean, dbByte и т . п . |
Updatable |
Returns a value that indicates whether you can change a DAO object. |
|