Working with Records

When working with data sources, the majority of your work revolves around adding, editing, or deleting records. In addition, you may find the need to retrieve many records at once. Let us begin learning how to work with records by learning how to add them to our recordset.

Adding New Records

To add a new record to a recordset, use the AddNew method. The AddNew method creates a new record at the end of your recordset and points the record pointer to it. The following code illustrates the most basic way in which the AddNew method can be used:

rst.Open "Authors", _
         "DSN=BiblioDSN", _
         adOpenKeyset, _
         adLockOptimistic

rst.AddNew
rst.Fields("Author") = "Jason"
rst.Fields("Year Born") = 1973
rst.Update

rst.Close

Notice that before the recordset is closed and after the information has been loaded into the fields of the recordset, the Update method is called. The Update method tells ADO that the record currently being edited is ready to be updated in the database.

The AddNew method can also be used with a set of parameters as shown in this example:

rst.Open "Authors", _
         "DSN=BiblioDSN", _
         adOpenKeyset, _
         adLockOptimistic

rst.AddNew "Author", "Kimberly"

rst.Close

This example passes two parameters to the AddNew method. The first parameter is the name of a field and the second parameter is the value for that field. There is no need to call the Update method when using this syntax because ADO knows that you are creating a new record with only one field value specified.

Finally, ...

Get ADO: ActiveX Data Objects now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.