Save 和 Open 方法示例 (VB)

这三个示例演示了如何将 SaveOpen 方法一起使用。

假设你正在进行商务旅行,并希望从数据库沿用表。 在转到之前,以 Recordset 的形式访问数据,并将其保存在可传输的表单中。 到达目标时,将访问 Recordset 作为本地断开连接 Recordset。 对 Recordset进行更改,然后再次保存。 最后,当你回家时,再次连接到数据库,并使用你在路上所做的更改进行更新。

首先,访问并保存 作者 表。

'BeginSaveVB  
  
    'To integrate this code  
    'replace the data source and initial catalog values  
    'in the connection string  
  
Public Sub Main()  
    On Error GoTo ErrorHandler  
  
    'recordset and connection variables  
    Dim rstAuthors As ADODB.Recordset  
    Dim Cnxn As ADODB.Connection  
    Dim strCnxn As String  
    Dim strSQLAuthors As String  
  
    ' Open connection  
    Set Cnxn = New ADODB.Connection  
    strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _  
        "Initial Catalog='Pubs';Integrated Security='SSPI';"  
    Cnxn.Open strCnxn  
  
    Set rstAuthors = New ADODB.Recordset  
    strSQLAuthors = "SELECT au_id, au_lname, au_fname, city, phone FROM Authors"  
    rstAuthors.Open strSQLAuthors, Cnxn, adOpenDynamic, adLockOptimistic, adCmdText  
  
    'For sake of illustration, save the Recordset to a diskette in XML format  
    rstAuthors.Save "c:\Pubs.xml", adPersistXML  
  
    ' clean up  
    rstAuthors.Close  
    Cnxn.Close  
    Set rstAuthors = Nothing  
    Set Cnxn = Nothing  
    Exit Sub  
  
ErrorHandler:  
    'clean up  
    If Not rstAuthors Is Nothing Then  
        If rstAuthors.State = adStateOpen Then rstAuthors.Close  
    End If  
    Set rstAuthors = Nothing  
  
    If Not Cnxn Is Nothing Then  
        If Cnxn.State = adStateOpen Then Cnxn.Close  
    End If  
    Set Cnxn = Nothing  
  
    If Err <> 0 Then  
        MsgBox Err.Source & "-->" & Err.Description, , "Error"  
    End If  
End Sub  
'EndSaveVB  

此时,你已到达目的地。 将 作者 表作为本地断开连接 Recordset访问。 您必须在用于访问已保存文件的计算机上具有 MSPersist 提供程序,即:\Pubs.xml。

Attribute VB_Name = "Save"  

最后,你回家了。 现在,使用更改更新数据库。

Attribute VB_Name = "Save"  

另请参阅

Open 方法 (ADO Recordset)
Recordset 对象 (ADO)
有关记录集持久性 的详细信息
Save 方法