ADO.NET is a set of .NET Framework classes that expose data access services to .NET Framework application developers. ADO.NET provides a comprehensive framework for working with data sources, both relational and non-relational. It enables applications to retrieve data from a data source, process that data, and then update the data source, all while maintaining data consistency.
ADO.NET components allow you to connect to a data source, execute commands, and retrieve data. The core objects for data access include:
Connection objects: Establish a connection to a data source. Different data providers (e.g., SQL Server, Oracle, OLE DB) have their own specific Connection objects (e.g., SqlConnection, OracleConnection).Command objects: Represent SQL statements or stored procedures to be executed against a data source. Like connections, these are provider-specific (e.g., SqlCommand, OracleCommand).DataReader objects: Provide a forward-only, read-only stream of data from the data source. This is an efficient way to retrieve large amounts of data.DataAdapter objects: Bridge the gap between a DataSet and a data source. They are used to fill a DataSet with data and to reconcile changes made to the DataSet back to the data source.DataSet objects: An in-memory representation of data that can hold multiple tables, relationships, and constraints. It's often used for disconnected data scenarios.The first step in accessing data is to establish a connection to the data source. This is done using a Connection object. You typically provide a connection string that specifies details like the server name, database name, authentication credentials, and the provider to use.
Here's an example using SqlConnection for SQL Server:
using System;
using System.Data.SqlClient;
public class ConnectionExample
{
public static void Main(string[] args)
{
string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
try
{
connection.Open();
Console.WriteLine("Connection successful!");
// You can now execute commands
}
catch (SqlException ex)
{
Console.WriteLine($"Error connecting to database: {ex.Message}");
}
}
}
}
Once a connection is established, you can use Command objects to execute SQL statements or stored procedures. The results can be retrieved using a DataReader or by populating a DataSet.
DataReaderThe DataReader is ideal for reading data sequentially. It's lightweight and efficient for scenarios where you just need to iterate through results.
using System;
using System.Data.SqlClient;
public class DataReaderExample
{
public static void Main(string[] args)
{
string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";
string query = "SELECT CustomerID, CompanyName FROM Customers";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(query, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine($"ID: {reader["CustomerID"]}, Name: {reader["CompanyName"]}");
}
}
}
}
}
}
DataAdapter and DataSetThe DataAdapter and DataSet provide a more flexible way to work with data, especially when dealing with disconnected scenarios or when you need to manipulate data in memory.
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 OrderID, OrderDate, ShipCountry FROM Orders";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter(query, connection);
DataSet dataSet = new DataSet();
try
{
connection.Open();
adapter.Fill(dataSet, "Orders"); // Fill the DataSet with data into a table named "Orders"
// Access data from the DataSet
DataTable ordersTable = dataSet.Tables["Orders"];
foreach (DataRow row in ordersTable.Rows)
{
Console.WriteLine($"Order ID: {row["OrderID"]}, Ship Country: {row["ShipCountry"]}");
}
}
catch (SqlException ex)
{
Console.WriteLine($"Error retrieving data: {ex.Message}");
}
}
}
}
DataAdapter, ensure you have appropriate commands set for InsertCommand, UpdateCommand, and DeleteCommand if you plan to update the data source.
ADO.NET supports a variety of data providers, each with its own set of classes derived from the common ADO.NET types. Common providers include:
System.Data.SqlClientSystem.Data.OleDb (for accessing OLE DB compliant data sources like Access)System.Data.Odbc (for accessing ODBC data sources)System.Data.OracleClient (though for newer Oracle versions, Oracle's own provider might be preferred)You can also find third-party providers for other databases like MySQL, PostgreSQL, etc.
using statement for disposable objects like Connection, Command, and DataReader to ensure resources are properly released.using statements helps with this.DataReader vs. DataSet) based on your application's needs.