Using the Connection Object

ADO and SQL Server

ADO and SQL Server

Using the Connection Object

In addition to the Command object, an application can use the Connection object to issue commands, stored procedures, and user-defined functions to a database as if they were native methods on the Connection object. To execute a query without using a Command object, an application can pass a query string to the Execute method of a Connection object.

However, a Command object is required if you want to save and re-execute the command text, or use query parameters.

To execute a command on the Connection object

  1. Assign a name to the command using the Name property of the Command object.

  2. Set the ActiveConnection property of the Command object to the connection.

  3. Issue a statement where the command name is used as if it were a method on the Connection object, followed by any parameters.

  4. Create a Recordset object if any rows are returned.

  5. Set the Recordset properties to customize the resulting Recordset.
Using the Connection Object to Execute Commands

This example shows how to use the Execute method of the Connection object to execute commands.

Dim cn As New ADODB.Connection
. . .
Dim rs As New ADODB.Recordset

cmd1 = txtQuery.Text
Set rs = cn.Execute(cmd1)

After the Connection and Recordset objects are created, the variable cmd1 is assigned the value of a user-supplied query string (txtQuery.Text) from a Microsoft Visual BasicĀ® form. The recordset is assigned the results of a query, by calling the Execute method of the Connection object, with the variable cmd1 used as the query string parameter.

See Also

Connection Object