ADO.NET Command Object

A Core Component for Executing Database Commands in .NET

Introduction to the Command Object

The Command object in ADO.NET is a fundamental component used to execute SQL statements or stored procedures against a data source. It represents a command to be run, such as a query to retrieve data, an update to modify data, or a call to a stored procedure.

Key responsibilities of a Command object include:

Core Properties and Methods

Properties

Methods

Working with the Command Object

Creating a Command

You typically create a Command object through a specific data provider's factory, such as SqlCommand for SQL Server or MySqlCommand for MySQL. The command object is usually instantiated with a CommandText and a Connection.

C# Example: Creating and Executing a Simple Query

using System;
using System.Data;
using Microsoft.Data.SqlClient; // Or your specific provider

public class CommandExample
{
    public static void ExecuteSimpleQuery(string connectionString)
    {
        string sql = "SELECT COUNT(*) FROM Customers";

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            using (SqlCommand command = new SqlCommand(sql, connection))
            {
                try
                {
                    connection.Open();
                    object result = command.ExecuteScalar();
                    Console.WriteLine($"Number of customers: {result}");
                }
                catch (SqlException ex)
                {
                    Console.WriteLine($"Error: {ex.Message}");
                }
            }
        }
    }
}

Using Parameters

Using parameters is crucial for security (to prevent SQL injection) and performance (as it allows the database to cache execution plans). Parameters are added to the Parameters collection of the Command object.

C# Example: Using Parameters with a Query

using System;
using System.Data;
using Microsoft.Data.SqlClient;

public class ParameterExample
{
    public static void GetDataByCustomerID(string connectionString, int customerId)
    {
        string sql = "SELECT CustomerName, Email FROM Customers WHERE CustomerID = @ID";

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            using (SqlCommand command = new SqlCommand(sql, connection))
            {
                // Add the parameter
                command.Parameters.AddWithValue("@ID", customerId);

                try
                {
                    connection.Open();
                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        if (reader.Read())
                        {
                            Console.WriteLine($"Name: {reader["CustomerName"]}, Email: {reader["Email"]}");
                        }
                        else
                        {
                            Console.WriteLine($"Customer with ID {customerId} not found.");
                        }
                    }
                }
                catch (SqlException ex)
                {
                    Console.WriteLine($"Error: {ex.Message}");
                }
            }
        }
    }
}

Executing Stored Procedures

To execute a stored procedure, set the CommandType to StoredProcedure and set the CommandText to the name of the stored procedure.

C# Example: Executing a Stored Procedure

using System;
using System.Data;
using Microsoft.Data.SqlClient;

public class StoredProcExample
{
    public static void UpdateProductPrice(string connectionString, int productId, decimal newPrice)
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            using (SqlCommand command = new SqlCommand("UpdateProductPriceSP", connection)) // Stored procedure name
            {
                command.CommandType = CommandType.StoredProcedure;

                // Add parameters for the stored procedure
                command.Parameters.AddWithValue("@ProductID", productId);
                command.Parameters.AddWithValue("@NewPrice", newPrice);

                try
                {
                    connection.Open();
                    int rowsAffected = command.ExecuteNonQuery();
                    Console.WriteLine($"{rowsAffected} row(s) updated.");
                }
                catch (SqlException ex)
                {
                    Console.WriteLine($"Error executing stored procedure: {ex.Message}");
                }
            }
        }
    }
}

Command Types

The CommandType enumeration provides flexibility in how the CommandText is interpreted:

Best Practices