Retrieving Data with ADO.NET

This section delves into the fundamental techniques for retrieving data from a data source using ADO.NET. ADO.NET provides a rich set of objects and classes that facilitate efficient data access and manipulation.

Core Objects for Data Retrieval

The primary objects involved in retrieving data are:

Using DbDataReader

The DbDataReader is the most efficient way to retrieve a forward-only stream of rows from a data source. It's ideal for scenarios where you need to process data row by row without loading the entire result set into memory.

Steps to Retrieve Data with DbDataReader:

  1. Create a DbConnection object and open the connection to your data source.
  2. Create a DbCommand object, associating it with the connection and setting the SQL query or stored procedure to execute.
  3. Execute the command using ExecuteReader(). This returns a DbDataReader object.
  4. Iterate through the rows using a while (reader.Read()) loop.
  5. Access column values within each row using the reader[columnName] or reader.GetOrdinal(columnName) syntax.
  6. Close the DbDataReader and then the DbConnection. It's good practice to use using statements to ensure proper disposal of these objects.
  7. Example: Retrieving Product Names (Conceptual C#)

    
    using System.Data.Common; // For generic DbProviderFactory
    using System.Data.SqlClient; // Example for SQL Server
    
    // ...
    
    using (DbConnection connection = new SqlConnection("YourConnectionString"))
    {
        connection.Open();
        string sql = "SELECT ProductName FROM Production.Product";
        using (DbCommand command = connection.CreateCommand())
        {
            command.CommandText = sql;
            using (DbDataReader reader = command.ExecuteReader())
            {
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        // Access the 'ProductName' column
                        string productName = reader["ProductName"].ToString();
                        Console.WriteLine(productName);
                    }
                }
            }
        }
    }