MSDN Documentation

ADO.NET: Connections and Commands

This document explores the fundamental components of ADO.NET for interacting with data sources: DbConnection and DbCommand objects. Understanding these objects is crucial for building data-driven applications.

DbConnection Objects

A DbConnection object represents a unique session with a data source. It is the first step in any ADO.NET operation, establishing a link to the database. Different data providers (e.g., SQL Server, Oracle, OLE DB) implement their own specific connection classes that inherit from the abstract DbConnection base class.

Key Properties and Methods:

Example: Opening a SQL Server Connection

This C# example demonstrates how to open a connection to a SQL Server database.


using System.Data.SqlClient;

// ...

string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";
SqlConnection connection = null;

try
{
    connection = new SqlConnection(connectionString);
    connection.Open();
    Console.WriteLine("Connection opened successfully!");
    Console.WriteLine("Connection State: " + connection.State);
}
catch (SqlException ex)
{
    Console.WriteLine("Error connecting to database: " + ex.Message);
}
finally
{
    if (connection != null && connection.State == System.Data.ConnectionState.Open)
    {
        connection.Close();
        Console.WriteLine("Connection closed.");
    }
}
            

DbCommand Objects

A DbCommand object represents a Transact-SQL statement or stored procedure to be executed against a data source. It is used to perform operations like querying data, inserting, updating, or deleting records.

Key Properties and Methods:

Example: Executing a SQL Query

This C# example demonstrates executing a SELECT statement and reading results.


using System.Data.SqlClient;

// Assume 'connection' is an already opened SqlConnection object

string sql = "SELECT CustomerID, CompanyName FROM Customers WHERE City = @City";

try
{
    using (SqlCommand command = new SqlCommand(sql, connection))
    {
        // Add parameter to prevent SQL injection
        command.Parameters.AddWithValue("@City", "London");

        using (SqlDataReader reader = command.ExecuteReader())
        {
            Console.WriteLine("Customers in London:");
            while (reader.Read())
            {
                Console.WriteLine($"- {reader["CompanyName"]} (ID: {reader["CustomerID"]})");
            }
        }
    }
}
catch (SqlException ex)
{
    Console.WriteLine("Error executing command: " + ex.Message);
}
            

Best Practices

Summary Table

Object Purpose Key Methods/Properties
DbConnection Establishes a session with a data source. ConnectionString, Open(), Close(), State
DbCommand Represents a statement to be executed. CommandText, Connection, Parameters, ExecuteReader(), ExecuteNonQuery(), ExecuteScalar()