Microsoft Docs

Documentation for Developers

DataAdapter Overview

The DataAdapter is a key component in ADO.NET that provides a bridge between a DataSet and a data source for retrieving and saving data. It acts as a mediator, abstracting the details of data manipulation operations.

What is a DataAdapter?

A DataAdapter is an object that, in conjunction with a DataSet, provides access to data in a data source. It is used to fill a DataSet and persist changes made to the data in the DataSet back to the data source. The DataAdapter uses commands and connections to a data source to retrieve data and send updates.

The DataAdapter object abstracts the data access operations. You can use it to:

Key Properties and Methods

The DataAdapter class provides several important properties and methods:

Common DataAdapter Implementations

ADO.NET provides specific implementations of the DataAdapter for various data sources:

Example Usage (Conceptual)

Here's a simplified conceptual example of how you might use a SqlDataAdapter to retrieve data:


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

// ...

string connectionString = "Server=myServer;Database=myDatabase;User ID=myUser;Password=myPassword;";
string sqlQuery = "SELECT CustomerID, CompanyName, ContactName FROM Customers";

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

    try
    {
        connection.Open();
        adapter.Fill(dataSet, "Customers"); // Fill the DataSet with data into a table named "Customers"

        // Now you can access the data in dataSet.Tables["Customers"]
        foreach (DataRow row in dataSet.Tables["Customers"].Rows)
        {
            Console.WriteLine($"{row["CustomerID"]}, {row["CompanyName"]}, {row["ContactName"]}");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"An error occurred: {ex.Message}");
    }
}
            

Note: When updating the data source, the DataAdapter typically uses optimistic concurrency control. This means it checks if the row in the data source has been modified since it was retrieved before applying an update or delete. If a conflict is detected, an exception is thrown, which can be handled to resolve the conflict.

DataAdapter vs. DataReader

It's important to understand the difference between a DataAdapter and a DataReader:

Choose the appropriate component based on your application's requirements for data access and manipulation.