MSDN Documentation

Command Objects in ADO.NET

Command objects are fundamental to interacting with data sources in ADO.NET. They represent SQL statements, stored procedures, or other commands that you want to execute against a database. The primary command objects are DbCommand (the abstract base class) and its concrete implementations like SqlCommand for SQL Server, OleDbCommand for OLE DB providers, and OdbcCommand for ODBC providers.

Key Properties of Command Objects

Command objects expose several important properties that control their behavior and execution:

Executing Commands

Command objects provide methods to execute various types of commands:

Example: Executing a SELECT Statement

Here's a C# example demonstrating how to use a SqlCommand to retrieve data:


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

public class CommandExample
{
    public static void GetCustomerNames(string connectionString)
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            string sql = "SELECT CustomerID, CompanyName FROM Customers WHERE Country = @Country";
            using (SqlCommand command = new SqlCommand(sql, connection))
            {
                // Add a parameter to prevent SQL injection
                command.Parameters.AddWithValue("@Country", "USA");

                try
                {
                    connection.Open();
                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        if (reader.HasRows)
                        {
                            while (reader.Read())
                            {
                                Console.WriteLine($"ID: {reader["CustomerID"]}, Name: {reader["CompanyName"]}");
                            }
                        }
                        else
                        {
                            Console.WriteLine("No customers found for the specified country.");
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"An error occurred: {ex.Message}");
                }
            }
        }
    }
}
            

Best Practices

Understanding and effectively using command objects is crucial for building robust and secure data-driven applications with ADO.NET.