MSDN Documentation

Command Objects in ADO.NET

Command objects are fundamental to interacting with databases in ADO.NET. They represent a SQL statement or a stored procedure that you can execute against a data source.

Core Command Objects

ADO.NET provides several classes for command objects, depending on the data provider you are using. The most common ones are:

While the specific classes differ, their core functionality and properties are largely the same.

Key Properties of Command Objects

Here are some of the most important properties you'll use with command objects:

CommandText

This property holds the SQL statement, stored procedure name, or table name to be executed.

// Example: SQL SELECT statement
command.CommandText = "SELECT CustomerID, CompanyName FROM Customers";

// Example: Stored Procedure
command.CommandText = "usp_GetOrdersByCustomerID";
command.CommandType = CommandType.StoredProcedure;

CommandType

This enumeration specifies how the CommandText should be interpreted.

Connection

This property holds the DbConnection object that the command will execute against. You must establish a connection before executing a command.

SqlConnection connection = new SqlConnection("YourConnectionString");
SqlCommand command = new SqlCommand("SELECT * FROM Products", connection);
connection.Open();
// ... execute command ...
connection.Close();

Parameters

This property is a collection of DbParameter objects that represent the parameters for the command, particularly useful for stored procedures and parameterized queries to prevent SQL injection.

// Example with a parameter
SqlCommand command = new SqlCommand("SELECT * FROM Orders WHERE CustomerID = @CustomerID", connection);
command.Parameters.AddWithValue("@CustomerID", "ALFKI");

Executing Commands

Command objects have methods to execute them:

ExecuteNonQuery()

Executes a command that does not return a result set, such as an INSERT, UPDATE, or DELETE statement. It returns the number of rows affected.

int rowsAffected = command.ExecuteNonQuery();
Console.WriteLine($"Rows affected: {rowsAffected}");

ExecuteReader()

Executes a command that returns a result set (like a SELECT statement). It returns a DbDataReader object, which provides a forward-only, read-only stream of data.

using (SqlDataReader reader = command.ExecuteReader())
{
    while (reader.Read())
    {
        Console.WriteLine($"{reader["CustomerID"]} - {reader["CompanyName"]}");
    }
}

ExecuteScalar()

Executes a command that returns a single value (e.g., a count or an aggregate function). It returns the value of the first column of the first row in the result set.

int customerCount = (int)command.ExecuteScalar();
Console.WriteLine($"Total customers: {customerCount}");

Best Practices

"The greatest glory in living lies not in never falling, but in rising every time we fall." - Nelson Mandela