次の方法で共有


名前付きコマンド

単純なコマンド の作成と実行は、コマンドを実行する 1 つの方法を示しています。 別の方法があります。名前付きコマンドにし、この名前付きコマンドを Connection オブジェクトで直接呼び出すことができます (Command オブジェクトの ActiveConnection プロパティに割り当てられます)。 コマンドの名前付けとは、Command オブジェクトの Name プロパティに名前を割り当てることを意味します。 例えば

objCmd.Name = "GetCustomers"  
objCmd.ActiveConnection = objConn  
objConn.GetCustomers objRs  

名前付きコマンドは、Connection オブジェクトの "カスタム メソッド" であるかのように機能します。 コマンドの結果は、この "カスタム メソッド" の out パラメーターとして返されます。

この機能の例を次に示します。

'BeginNamedCmd  
    On Error GoTo ErrHandler:  
  
    Dim objConn As New ADODB.Connection  
    Dim objCmd As New ADODB.Command  
    Dim objRs As New ADODB.Recordset  
  
    ' Connect to the data source.  
    Set objConn = GetNewConnection  
  
    objCmd.CommandText = "SELECT CustomerID, CompanyName FROM Customers"  
    objCmd.CommandType = adCmdText  
  
    'Name the command.  
    objCmd.Name = "GetCustomers"  
  
    objCmd.ActiveConnection = objConn  
  
    ' Execute using Command.Name from the Connection.  
    objConn.GetCustomers objRs  
  
    ' Display.  
    Do While Not objRs.EOF  
        Debug.Print objRs(0) & vbTab & objRs(1)  
        objRs.MoveNext  
    Loop  
  
    'clean up  
    objRs.Close  
    objConn.Close  
    Set objRs = Nothing  
    Set objConn = Nothing  
    Set objCmd = Nothing  
    Exit Sub  
  
ErrHandler:  
    'clean up  
    If objRs.State = adStateOpen Then  
        objRs.Close  
    End If  
  
    If objConn.State = adStateOpen Then  
        objConn.Close  
    End If  
  
    Set objRs = Nothing  
    Set objConn = Nothing  
    Set objCmd = Nothing  
  
    If Err <> 0 Then  
        MsgBox Err.Source & "-->" & Err.Description, , "Error"  
    End If  
'EndNamedCmd  

関連項目

コネクションオブジェクト (ADO)