Save および Open メソッドの例 (VB)

これらの 3 つの例は、Save および Open メソッドを一緒に使う方法を示しています。

あなたは出張に出かけ、あるデータベースのテーブルを持って行きたいとします。 あなたは出かける前に、Recordset としてデータにアクセスし、持ち運び可能な形で保存します。 目的地に着いたら、ローカルの切断された Recordset として Recordset にアクセスします。 Recordset に変更を加え、もう一度保存します。 最後に、帰宅したら、再びデータベースに接続し、外出先で加えた変更を反映します。

まず、Authors テーブルにアクセスして保存します。

'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  

この時点で、あなたは目的地に到着しています。 Authors テーブルには、ローカルの切断された Recordset としてアクセスします。 保存したファイル a:\Pubs.xml にアクセスするには、使うコンピューターに MSPersist プロバイダーをインストールしておく必要があります。

Attribute VB_Name = "Save"  

最後に、帰宅します。 次に、データベースに変更内容を反映します。

Attribute VB_Name = "Save"  

参照

Open メソッド (ADO Recordset)
Recordset オブジェクト (ADO)
レコードセットの保持に関する詳細情報
Save メソッド