DataAdapter Class
The DataAdapter
class in ADO.NET is a bridge between a data source and a DataSet
. It is used to retrieve data from a data source and to save data changes back to the data source.
Overview
The DataAdapter
plays a crucial role in the disconnected data access model of ADO.NET. It encapsulates the logic for interacting with a specific data source technology (like SQL Server, Oracle, etc.) and performing operations such as:
- Filling a
DataSet
orDataTable
with data from the data source. - Updating the data source with changes made to a
DataSet
orDataTable
.
Each ADO.NET provider typically includes its own implementation of the DataAdapter
, such as SqlDataAdapter
for SQL Server and OleDbDataAdapter
for OLE DB data sources.
Key Properties and Methods
Properties
- SelectCommand: A
Command
object that retrieves records from the data source. - InsertCommand: A
Command
object that executes an SQL INSERT statement to add new records to the data source. - UpdateCommand: A
Command
object that executes an SQL UPDATE statement to modify existing records in the data source. - DeleteCommand: A
Command
object that executes an SQL DELETE statement to remove records from the data source. - MissingMappingAction: Specifies how the
DataAdapter
should handle missing mappings between the data source and theDataSet
. - MissingSchemaAction: Specifies how the
DataAdapter
should handle missing schema information in theDataSet
.
Methods
- Fill(DataSet dataSet): Populates a
DataSet
with the results of executing theSelectCommand
. - Fill(DataTable dataTable): Populates a specified
DataTable
with the results of executing theSelectCommand
. - Fill(DataSet dataSet, string srcTable): Populates a
DataSet
with the results of executing theSelectCommand
, using the specified source table name. - Update(DataSet dataSet): Updates the data source with the changes made to the specified
DataSet
. - Update(DataTable dataTable): Updates the data source with the changes made to the specified
DataTable
.
Example Usage
Here's a simplified example of how to use SqlDataAdapter
to retrieve data into a DataSet
:
using System;
using System.Data;
using System.Data.SqlClient;
public class DataAdapterExample
{
public static void Main(string[] args)
{
string connectionString = "YourConnectionStringHere"; // e.g., "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;"
string query = "SELECT CustomerID, CompanyName, ContactName FROM Customers";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter(query, connection);
DataSet customerData = new DataSet();
try
{
connection.Open();
adapter.Fill(customerData, "Customers"); // Fills the DataSet with a table named "Customers"
Console.WriteLine("Data retrieved successfully:");
foreach (DataRow row in customerData.Tables["Customers"].Rows)
{
Console.WriteLine($"ID: {row["CustomerID"]}, Company: {row["CompanyName"]}, Contact: {row["ContactName"]}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
}
Updating Data Source
To update the data source, you first modify the data in the DataSet
or DataTable
, and then call the Update
method of the DataAdapter
. The DataAdapter
inspects the changes and executes the appropriate InsertCommand
, UpdateCommand
, or DeleteCommand
for each modified row.
// Assuming 'customerData' is a DataSet previously filled and modified
// ... modification code here ...
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand insertCommand = new SqlCommand("INSERT INTO Customers (CustomerID, CompanyName, ContactName) VALUES (@CustomerID, @CompanyName, @ContactName)", connection);
insertCommand.Parameters.Add("@CustomerID", SqlDbType.Int, 0, "CustomerID");
insertCommand.Parameters.Add("@CompanyName", SqlDbType.VarChar, 40, "CompanyName");
insertCommand.Parameters.Add("@ContactName", SqlDbType.VarChar, 30, "ContactName");
SqlCommand updateCommand = new SqlCommand("UPDATE Customers SET CompanyName = @CompanyName, ContactName = @ContactName WHERE CustomerID = @CustomerID", connection);
updateCommand.Parameters.Add("@CustomerID", SqlDbType.Int, 0, "CustomerID");
updateCommand.Parameters.Add("@CompanyName", SqlDbType.VarChar, 40, "CompanyName");
updateCommand.Parameters.Add("@ContactName", SqlDbType.VarChar, 30, "ContactName");
SqlCommand deleteCommand = new SqlCommand("DELETE FROM Customers WHERE CustomerID = @CustomerID", connection);
deleteCommand.Parameters.Add("@CustomerID", SqlDbType.Int, 0, "CustomerID");
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.InsertCommand = insertCommand;
adapter.UpdateCommand = updateCommand;
adapter.DeleteCommand = deleteCommand;
try
{
connection.Open();
int rowsAffected = adapter.Update(customerData, "Customers"); // Update the data source
Console.WriteLine($"{rowsAffected} rows updated.");
}
catch (SqlException ex)
{
Console.WriteLine($"Error updating database: {ex.Message}");
// Handle potential conflicts or errors during update
}
}
Events
The DataAdapter
class also supports events that allow you to intercept and handle operations during the Fill
and Update
processes:
- RowUpdating: Fired before an update is made to a row.
- RowUpdated: Fired after an update is made to a row.
- FillError: Fired when a row-level error occurs during a
Fill
operation.
Conclusion
The DataAdapter
is a powerful component of ADO.NET, facilitating the efficient transfer of data between a data source and your application's memory. By leveraging its capabilities, you can build robust and responsive data-driven applications.