ADO.NET Command Class
The Command classes in ADO.NET are fundamental for interacting with data sources. They represent an SQL statement or stored procedure to be executed against a data source.
Core Concepts
The primary classes involved in commanding are:
DbCommand: An abstract base class providing common functionality for command objects.SqlCommand(for SQL Server): Represents an SQL statement or stored procedure.OleDbCommand(for OLE DB providers): Represents an OLE DB command.OdbcCommand(for ODBC providers): Represents an ODBC command.
Key properties and methods of a Command object include:
CommandText: The SQL statement or stored procedure name to execute.CommandType: Specifies how theCommandTextproperty should be interpreted (e.g.,Textfor SQL,StoredProcedurefor a stored procedure).Connection: TheDbConnectionobject associated with the command.Parameters: A collection of parameters for the command.ExecuteReader(): Executes the command and returns aDbDataReader.ExecuteNonQuery(): Executes the command and returns the number of rows affected.ExecuteScalar(): Executes the command and returns the first column of the first row in the result set.
Creating and Executing Commands
Here's a typical workflow for creating and executing a command:
- Create a
DbConnectionobject and open it. - Create a
DbCommandobject, setting itsConnection,CommandText, andCommandType. - (Optional) Add any necessary parameters to the command's
Parameterscollection. - Execute the command using one of the appropriate execution methods (
ExecuteReader,ExecuteNonQuery, orExecuteScalar). - Process the results.
- Close the connection.
Example: Executing a SELECT Statement
C# Example
using System;
using System.Data;
using System.Data.SqlClient;
public class CommandExample
{
public static void ReadData(string connectionString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
// Open the connection
connection.Open();
// Create a SqlCommand object
string sql = "SELECT CustomerID, CompanyName FROM Customers WHERE City = @City";
using (SqlCommand command = new SqlCommand(sql, connection))
{
// Set the CommandType
command.CommandType = CommandType.Text;
// Add a parameter
command.Parameters.AddWithValue("@City", "London");
// Execute the command and get a DataReader
using (SqlDataReader reader = command.ExecuteReader())
{
Console.WriteLine("Customers in London:");
while (reader.Read())
{
Console.WriteLine($"- ID: {reader["CustomerID"]}, Name: {reader["CompanyName"]}");
}
}
}
}
}
}
Example: Executing a Non-Query Statement (INSERT)
C# Example
using System;
using System.Data;
using System.Data.SqlClient;
public class CommandExample
{
public static int AddNewProduct(string connectionString, string productName, decimal price)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string sql = "INSERT INTO Products (ProductName, UnitPrice) VALUES (@ProductName, @UnitPrice)";
using (SqlCommand command = new SqlCommand(sql, connection))
{
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("@ProductName", productName);
command.Parameters.AddWithValue("@UnitPrice", price);
// Execute the command and get the number of rows affected
int rowsAffected = command.ExecuteNonQuery();
Console.WriteLine($"{rowsAffected} row(s) inserted.");
return rowsAffected;
}
}
}
}
Using Stored Procedures
To execute a stored procedure, set the CommandType to CommandType.StoredProcedure and set the CommandText to the name of the stored procedure.
C# Example (Stored Procedure)
using System;
using System.Data;
using System.Data.SqlClient;
public class CommandExample
{
public static int GetCustomerCountByCity(string connectionString, string city)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
// Assume a stored procedure named 'sp_GetCustomerCountByCity' exists
using (SqlCommand command = new SqlCommand("sp_GetCustomerCountByCity", connection))
{
command.CommandType = CommandType.StoredProcedure;
// Add input parameter
command.Parameters.AddWithValue("@CityName", city);
// Add output parameter (assuming the SP returns a count)
SqlParameter returnParameter = command.Parameters.Add("@CustomerCount", SqlDbType.Int);
returnParameter.Direction = ParameterDirection.Output;
command.ExecuteNonQuery(); // Execute the stored procedure
return (int)command.Parameters["@CustomerCount"].Value;
}
}
}
}
Best Practices
- Always use parameterized queries to prevent SQL injection vulnerabilities.
- Use
usingstatements forConnection,Command, andDataReaderobjects to ensure they are properly disposed of. - Set the appropriate
CommandType. - Choose the correct execution method based on your needs (
ExecuteReaderfor result sets,ExecuteNonQueryfor DML statements,ExecuteScalarfor single values).