Using the ADO Command Object

This sample project demonstrates how to create and execute a Command object using ADO 2.1.

Download a copy of the project.

Making the Command Object Project

  1. Create a DSN referring to the Northwind database. For information on creating DSNs, see these two MSDN Help topics:
  2. Open a new project in Visual Basic 6.0, and add a reference to the Microsoft ActiveX Data Objects 2.1 Library.
  3. Add a command button and a label to the form.
  4. Copy the following code into the form.

    Option Explicit

    Private Sub Command1_Click()
        Dim cnNWind As ADODB.Connection
        Dim rsNWind As ADODB.Recordset
        Dim cmNWind As ADODB.Command

        'Instantiate the Command and Connection objects.
        Set cnNWind = New Connection
        Set cmNWind = New Command

        'Open the connection using the Northwind DSN.
        cnNWind.Open "northwind"

        'Attach the connection to the Command object.
        Set cmNWind.ActiveConnection = cnNWind

        'Set command text and compile the command.
        With cmNWind
            .CommandText = "SELECT productname FROM products"
            .Prepared = True
        End With

        'Execute the command and display the results.
        Set rsNWind = cmNWind.Execute
        Set Label1.DataSource = rsNWind
        Label1.DataField = "ProductName"

        'Clean up.
        Set cmNWind = Nothing
        Set rsNWind = Nothing
        Set cnNWind = Nothing

    End Sub
  5. Save the project, then run it.
Last changed 9/17/00.