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 形式存取 [作者] 資料表。 您必須在用來存取已儲存檔案 (a:\Pubs.xml) 的電腦上擁有 MSPersist 提供者。

Attribute VB_Name = "Save"  

最後,請返回首頁。 現在,請使用您的變更來更新資料庫。

Attribute VB_Name = "Save"  

另請參閱

Open 方法 (ADO Recordset)
Recordset 物件 (ADO)
深入了解資料錄集的保存
Save 方法