Microsoft Learn

DataCommand in ADO.NET

The DataCommand class is a fundamental component of ADO.NET, representing a SQL statement or stored procedure that you want to execute against a data source.

Overview

A DataCommand object is used to encapsulate the details of executing a command, such as:

Key Properties

Here are some of the most important properties of a DataCommand object:

Key Methods

The primary methods for executing a DataCommand are:

Example: Executing a SELECT Statement

This example demonstrates how to use DataCommand to retrieve data using a SELECT statement.


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

public class DataCommandExample
{
    public static void Main(string[] args)
    {
        string connectionString = "YourConnectionStringHere"; // Replace with your actual connection string

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();

            // Define the SQL query
            string sqlQuery = "SELECT CustomerID, CompanyName FROM Customers WHERE City = @City";

            // Create a DataCommand object
            using (SqlCommand command = new SqlCommand(sqlQuery, connection))
            {
                // Set the CommandType (optional for text queries, but good practice)
                command.CommandType = CommandType.Text;

                // Add a parameter to the command
                command.Parameters.AddWithValue("@City", "London");

                Console.WriteLine("Customers in London:");

                // Execute the command and get a DataReader
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    // Loop through the results
                    while (reader.Read())
                    {
                        Console.WriteLine($"- ID: {reader["CustomerID"]}, Name: {reader["CompanyName"]}");
                    }
                }
            }
        }
    }
}
            

Example: Executing an INSERT Statement

This example shows how to use DataCommand to insert data into a table.


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

public class DataCommandInsertExample
{
    public static void Main(string[] args)
    {
        string connectionString = "YourConnectionStringHere";

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();

            string insertQuery = "INSERT INTO Products (ProductName, UnitPrice) VALUES (@Name, @Price)";

            using (SqlCommand command = new SqlCommand(insertQuery, connection))
            {
                command.CommandType = CommandType.Text;

                // Add parameters for the new product
                command.Parameters.AddWithValue("@Name", "New Gadget");
                command.Parameters.AddWithValue("@Price", 19.99);

                // Execute the command and get the number of rows affected
                int rowsAffected = command.ExecuteNonQuery();

                Console.WriteLine($"{rowsAffected} row(s) inserted successfully.");
            }
        }
    }
}
            
Note: Replace Microsoft.Data.SqlClient with the appropriate namespace for your specific data provider (e.g., System.Data.SqlClient, Npgsql, MySql.Data.MySqlClient).

Best Practices

Stored Procedures

When executing stored procedures, set CommandType to CommandType.StoredProcedure and set CommandText to the name of the stored procedure.


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

public class DataCommandStoredProcExample
{
    public static void Main(string[] args)
    {
        string connectionString = "YourConnectionStringHere";

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();

            using (SqlCommand command = new SqlCommand("usp_GetCustomerOrders", connection))
            {
                command.CommandType = CommandType.StoredProcedure;
                command.Parameters.AddWithValue("@CustomerID", "ALFKI");

                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        Console.WriteLine($"Order ID: {reader["OrderID"]}, Order Date: {reader["OrderDate"]}");
                    }
                }
            }
        }
    }
}