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
ObjectsA 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.
ConnectionString
: A string containing parameters required to establish the connection (e.g., server name, database name, authentication details).ConnectionTimeout
: The time in seconds to wait for a connection to be established before terminating the attempt.State
: Returns the current state of the connection (e.g., Open
, Closed
).Open()
: Opens the database connection.Close()
: Closes the database connection. It's important to always close connections when they are no longer needed to release resources.Dispose()
: Releases all resources used by the 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
ObjectsA 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.
Connection
: Specifies the DbConnection
object to execute the command against.CommandText
: The SQL statement or stored procedure name.CommandType
: Specifies how the CommandText
property is to be interpreted (e.g., Text
for SQL statements, StoredProcedure
for stored procedures).Parameters
: A collection of parameters associated with the command. Using parameters is highly recommended to prevent SQL injection vulnerabilities and improve performance.ExecuteReader()
: Executes the command and returns a DbDataReader
object.ExecuteNonQuery()
: Executes the command and returns the number of rows affected. Useful for INSERT, UPDATE, DELETE statements.ExecuteScalar()
: Executes the command and returns the value of the first column of the first row in the result set. Useful for aggregate functions like COUNT(*) or SUM().ExecuteResultSet()
: (Less common, often handled by DataAdapters) Executes the command and returns data.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);
}
using
statements: This ensures that resources (like connections and commands) are properly disposed of, even if errors occur.DbParameter
objects to pass values to your SQL statements. This is critical for security and performance.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() |