Connection Object Overview

The Connection object, like all provider-specific ADO.NET objects, comes in more than one version. You use the version that’s tailored for your specific data source. Here are two examples:

Every Connection object that accesses relational databases implements the common System.Data.IDbConnection interface. By looking at the IDbConnection interface, you’ll quickly see the small set of properties and methods that every Connection object is guaranteed to support (see Tables 3-1 and 3-2). The most important of these are the Close( ) and Open( ) methods, and the ConnectionString property, which specifies a variety of options about the data source and how to connect to it. All IDbConnection properties are read-only, except ConnectionString.

Table 3-1. IDbConnection properties
Table 3-2. IDbConnection methods

Member

Description

BeginTransaction( )

Programmatically starts a database transaction. Database transactions are detailed in Chapter 16.

ChangeDatabase( )

Sets a new database to be used for subsequent operations. Alternatively, you can execute the SQL USE command with SQL Server. Oracle databases don’t support this method.

CreateCommand( )

Returns a provider-specific IDbCommand object that is set to use this connection. This method is primarily useful when writing provider-agnostic code.

Open() and Close( )

Attempts to connect to or disconnect from the data source.

Other providers add additional members. For example, most Connection objects add the ServerVersion property (which contains a string with version information for the database product) and two events: StateChange (which fires when the connection is opened or closed) and InfoMessage (which fires when warning or error messages are received). SqlConnection also adds a WorkstationId and PacketSize property with additional information. For complete information about provider-specific members, refer to Part III.