Commands and Parameters in ADO.NET
This section delves into the core components of executing commands against a data source in ADO.NET: the Command
object and its associated Parameter
objects.
The Command Object
The Command
object represents a SQL statement or stored procedure to be executed against a data source. ADO.NET provides provider-specific implementations for commands, such as SqlCommand
for SQL Server, OleDbCommand
for OLE DB, and OdbcCommand
for ODBC.
Key Properties of a Command Object:
CommandText
: A string containing the SQL statement or the name of the stored procedure.CommandType
: Specifies how theCommandText
property is to be interpreted. Common values includeText
(for SQL statements),StoredProcedure
, andTableDirect
.Connection
: An instance of a connection object (e.g.,SqlConnection
) that establishes a link to the data source.Parameters
: A collection ofParameter
objects used to pass values to the command.Transaction
: The transaction within which the command executes.
Executing Commands:
Commands can be executed using several methods, depending on the expected outcome:
ExecuteNonQuery()
: Executes a command that returns no rows, such as anINSERT
,UPDATE
, orDELETE
statement. It returns the number of rows affected.ExecuteReader()
: Executes a command that returns a result set and returns aDataReader
object (e.g.,SqlDataReader
) to iterate through the rows.ExecuteScalar()
: Executes a command that returns a single value (e.g., the result of an aggregate function likeCOUNT(*)
) and returns the first column of the first row in the result set.ExecuteXmlReader()
: Executes a command that returns XML data and returns anXmlReader
object.
Parameters
Using parameters is crucial for security (preventing SQL injection) and performance (allowing the database to cache execution plans). Parameters are represented by the Parameter
object (e.g., SqlParameter
).
Key Properties of a Parameter Object:
ParameterName
: The name of the parameter, typically prefixed with '@' or '?'.DbType
: The data type of the parameter in the data source.Direction
: Indicates whether the parameter is an input, output, input/output, or return value parameter.Value
: The actual value to be passed to the parameter.Size
: The maximum size of the parameter value.
Adding Parameters:
Parameters are added to the Parameters
collection of the Command
object.
using System.Data;
using System.Data.SqlClient;
// ...
using (SqlConnection connection = new SqlConnection("YourConnectionString"))
{
connection.Open();
string sql = "SELECT CustomerName FROM Customers WHERE City = @City";
using (SqlCommand command = new SqlCommand(sql, connection))
{
// Add a parameter
command.Parameters.AddWithValue("@City", "London");
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(reader["CustomerName"]);
}
}
}
}
Output Parameters
Output parameters allow stored procedures to return values back to the application. They are declared with Direction.Output
.
using System.Data;
using System.Data.SqlClient;
// ...
using (SqlConnection connection = new SqlConnection("YourConnectionString"))
{
connection.Open();
using (SqlCommand command = new SqlCommand("GetCustomerCountByCity", connection))
{
command.CommandType = CommandType.StoredProcedure;
// Input parameter
command.Parameters.AddWithValue("@City", "Berlin");
// Output parameter
SqlParameter outputParameter = new SqlParameter("@CustomerCount", SqlDbType.Int);
outputParameter.Direction = ParameterDirection.Output;
command.Parameters.Add(outputParameter);
command.ExecuteNonQuery();
int customerCount = (int)outputParameter.Value;
Console.WriteLine($"Number of customers in Berlin: {customerCount}");
}
}
Best Practices
- Always use parameterized queries to prevent SQL injection.
- Set the appropriate
CommandType
. - Close connections and dispose of command and reader objects properly using
using
statements or explicitDispose()
calls. - Choose the most efficient
Execute...
method for your needs.