DataConnection Class

The DataConnection class in ADO.NET represents an open connection to a data source. It is the foundation for interacting with databases and other data stores. It provides a consistent way to manage connections across different data providers.

Key Concepts

Common Operations

Establishing a Connection

To establish a connection, you typically instantiate a specific provider's connection object (e.g., SqlConnection, OracleConnection) and provide a connection string.

using System.Data.SqlClient;

// Example using SQL Server
string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
    try
    {
        connection.Open();
        Console.WriteLine("Connection opened successfully.");
        // Perform database operations here
    }
    catch (SqlException ex)
    {
        Console.WriteLine($"Error connecting to database: {ex.Message}");
    }
} // Connection is automatically closed and disposed here

Opening and Closing Connections

The Open() and Close() methods are used to manage the connection state:

void Open()

Opens the database connection.

void Close()

Closes the connection.

Connection State

The State property indicates the current status of the connection.

ConnectionState State { get; }

Returns a ConnectionState enumeration value (e.g., ConnectionState.Open, ConnectionState.Closed).

Connection String

The ConnectionString property holds the string used to connect to the data source.

string ConnectionString { get; set; }

Provider-Specific Implementations

ADO.NET uses a factory pattern for creating connection objects. You'll typically work with concrete implementations:

Best Practices

Example: Using DataConnection with a Command

using System.Data.SqlClient;

string connectionString = "Server=myServerAddress;Database=myDataBase;Integrated Security=SSPI;";
string query = "SELECT COUNT(*) FROM Customers";

using (SqlConnection connection = new SqlConnection(connectionString))
{
    try
    {
        connection.Open();
        Console.WriteLine($"Connection state: {connection.State}");

        using (SqlCommand command = new SqlCommand(query, connection))
        {
            object result = command.ExecuteScalar();
            if (result != null)
            {
                Console.WriteLine($"Number of customers: {result}");
            }
        }
    }
    catch (SqlException ex)
    {
        Console.WriteLine($"Database error: {ex.Message}");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"General error: {ex.Message}");
    }
} // Connection is closed and disposed here

The DataConnection class is fundamental to ADO.NET, enabling efficient and reliable access to your data.