MSDN Documentation

Microsoft Developer Network

Retrieving Data with ADO.NET

This document explains how to retrieve data from a data source using ADO.NET. ADO.NET provides a rich set of components for data access, enabling you to connect to various data sources and manipulate data effectively.

Using DataReaders

DataReader objects provide a forward-only, read-only stream of data. They are the most efficient way to retrieve a large result set when you need to process each record sequentially.

Note: DataReaders are generally preferred over DataSets for simple data retrieval scenarios where you only need to read the data and don't require disconnected operation or the ability to edit the data in memory.

Example: Using SqlDataReader

The following example demonstrates how to use SqlDataReader to retrieve data from a SQL Server database.

using System;
using System.Data.SqlClient;

public class DataRetrievalExample
{
    public static void Main(string[] args)
    {
        string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";
        string query = "SELECT CustomerID, CompanyName, ContactName FROM Customers;";

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            SqlCommand command = new SqlCommand(query, connection);

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

Using DataSets and DataAdapters

For scenarios requiring disconnected data retrieval, manipulation, or synchronization between a client and server, DataSet and DataAdapter objects are invaluable. A DataAdapter acts as a bridge between a DataSet and a data source, filling the DataSet with data and reconciling changes made in the DataSet back to the data source.

Example: Using SqlDataAdapter and DataSet

This example shows how to populate a DataSet using SqlDataAdapter.

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

public class DataSetExample
{
    public static void Main(string[] args)
    {
        string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";
        string query = "SELECT ProductID, ProductName, UnitPrice FROM Products;";

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            SqlDataAdapter adapter = new SqlDataAdapter(query, connection);
            DataSet dataSet = new DataSet();

            try
            {
                adapter.Fill(dataSet, "Products"); // Fill the DataSet with data

                // Accessing data from the DataSet
                foreach (DataRow row in dataSet.Tables["Products"].Rows)
                {
                    Console.WriteLine($"ID: {row["ProductID"]}, Product: {row["ProductName"]}, Price: {row["UnitPrice"]}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
        }
    }
}

Key Components for Data Retrieval

Tip: Always use using statements for ADO.NET objects like connections and commands to ensure that resources are properly disposed of, even if errors occur.