这三个范例演示如何配合使用 Save 和 Open 方法。
假设用户在出差时需要携带数据库中的一个表。在出发前,用户以 Recordset 访问数据,并将其保存为便携格式。在到达目的地后,用户以本地、断开连接的方式访问 Recordset,在修改 Recordset 后将其保存。最后,当用户回家后,再次连接数据库并用旅途中所做的更改对其进行更新。
Public Sub Main()
SaveX1
SaveX2
SaveX3
End Sub
首先,访问并保存 Authors 表。
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
现在用户已到达目的地。以本地、断开连接的 Recordset 访问 Authors 表。请注意,要访问保存的文件 a:\Pubs.xml,必须在用户使用的机器上装有 MSPersist 提供者。
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
最后用户回到家里。现在用所做的更改更新数据库。
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