ADO.NET Commands

This document provides an in-depth look at ADO.NET Commands, a fundamental component for interacting with databases. Commands are used to execute SQL statements or stored procedures against a data source.

What are ADO.NET Commands?

An ADO.NET Command object represents a SQL statement or stored procedure that you want to execute against a data source. You can use command objects to perform operations such as retrieving data, inserting, updating, or deleting records, and executing stored procedures.

The primary classes for commands in ADO.NET are:

  • DbCommand (abstract base class)
  • SqlCommand (for SQL Server)
  • OleDbCommand (for OLE DB providers)
  • OdbcCommand (for ODBC providers)
  • OracleCommand (for Oracle)
  • MySqlCommand (for MySQL)

Creating and Executing Commands

To execute a command, you typically follow these steps:

  1. Create a DbConnection object and open the connection.
  2. Create a Command object (e.g., SqlCommand) and associate it with the connection.
  3. Set the CommandText property to the SQL statement or stored procedure name.
  4. Optionally, set the CommandType property (e.g., Text, StoredProcedure, TableDirect).
  5. Add any necessary parameters using the Parameters collection.
  6. Execute the command using methods like ExecuteNonQuery(), ExecuteReader(), or ExecuteScalar().
  7. Close the connection when done.

Example: Executing a SELECT Statement

This example demonstrates how to execute a SELECT statement to retrieve data.


using System;
using System.Data;
using Microsoft.Data.SqlClient; // For SQL Server

public class CommandExample
{
    public static void Main(string[] args)
    {
        string connectionString = "Server=your_server;Database=your_database;User Id=your_user;Password=your_password;";

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            string sqlQuery = "SELECT CustomerID, CompanyName FROM Customers WHERE City = @City";

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

                try
                {
                    connection.Open();
                    Console.WriteLine("Connection opened successfully.");

                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        if (reader.HasRows)
                        {
                            while (reader.Read())
                            {
                                Console.WriteLine($"ID: {reader["CustomerID"]}, Name: {reader["CompanyName"]}");
                            }
                        }
                        else
                        {
                            Console.WriteLine("No rows found.");
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error: {ex.Message}");
                }
            }
        }
    }
}
                

Command Execution Methods

ADO.NET provides several methods to execute commands, each suited for different scenarios:

Example: Executing an INSERT Statement

This example shows how to use ExecuteNonQuery() to insert a new record.


string insertQuery = "INSERT INTO Products (ProductName, UnitPrice) VALUES (@Name, @Price)";
using (var command = new SqlCommand(insertQuery, connection))
{
    command.Parameters.AddWithValue("@Name", "Chai");
    command.Parameters.AddWithValue("@Price", 18.00m);
    int result = command.ExecuteNonQuery();
    Console.WriteLine($"{result} row(s) inserted.");
}
                

Example: Executing a Stored Procedure

Executing stored procedures is common for complex database operations.


using (var command = new SqlCommand("usp_GetProductCountBySupplier", connection))
{
    command.CommandType = CommandType.StoredProcedure;
    command.Parameters.AddWithValue("@SupplierID", 5);

    object count = command.ExecuteScalar();
    Console.WriteLine($"Product count: {count}");
}
                

Command Properties

Key properties of a DbCommand object include:

Properly using command objects, including parameterization and choosing the correct execution method, is crucial for building efficient and secure data access applications in .NET.