Save and Open Methods Example (VB)

Microsoft ActiveX Data Objects (ADO)

Save and Open Methods Example (VB)

These three examples demonstrate how the Save and Open methods can be used together.

Assume you are going on a business trip and want to take along a table from a database. Before you go, you access the data as a Recordset and save it in a transportable form. When you arrive at your destination, you access the Recordset as a local, disconnected Recordset. You make changes to the Recordset, then save it again. Finally, when you return home, you connect to the database again and update it with the changes you made on the road.

Public Sub Main()
    SaveX1
    SaveX2
    SaveX3
End Sub

First, access and save the Authors table.

Public Sub SaveX1()
Dim rst As ADODB.Recordset
Set rst = New ADODB.Recordset

rst.Open "SELECT au_id, au_lname, au_fname, phone FROM Authors", _
         "Provider=SQLOLEDB;Data Source=MySrvr;User Id=uid;" & _
         "Password=pwd;Initial Catalog=pubs;" _
         adOpenDynamic, adLockOptimistic, adCmdText

'For sake of illustration, save the Recordset to a diskette in XML
'format.
rst.Save "a:\Pubs.xml", adPersistXML

rst.Close
End Sub

At this point, you have arrived at your destination. You will access the Authors table as a local, disconnected Recordset. Don't forget you must have the MSPersist provider on the machine that you are using in order to access the saved file, a:\Pubs.xml.

Public Sub SaveX2()
Dim rst As ADODB.Recordset
Set rst = New ADODB.Recordset

'For sake of illustration, we specify all parameters.
rst.Open "a:\Pubs.xml", "Provider=MSPersist;", , , adCmdFile

'Now you have a local, disconnected Recordset. Edit it as you desire.
'(In this example, the change makes no difference).
rst.Find "au_lname = 'Carson'"
If rst.EOF Then
    Debug.Print "Name not found."
    Exit Sub
End If

rst!city = "Berkeley"
rst.Update

'Save changes in ADTG format this time, purely for sake of illustration.
'Note that the previous version is still on the diskette, as a:\Pubs.xml.
rst.Save "a:\Pubs.adtg", adPersistADTG
rst.Close
End Sub

Finally, you return home. Now update the database with your changes.

Public Sub SaveX3()
Dim cnn As New ADODB.Connection
Dim rst As ADODB.Recordset
Set rst = New ADODB.Recordset

'If there is no ActiveConnection, you can open with defaults.
rst.Open "a:\Pubs.adtg"

'Connect to the database, associate the Recordset with the connection, 
'then update the database table with the changed Recordset.
cnn.Open "Provider=SQLOLEDB;Data Source=MySrvr;User Id=uid;" & _
         "Password=pwd;Initial Catalog=pubs;"
rst.ActiveConnection = cnn
rst.UpdateBatch

rst.Close
cnn.Close
End Sub