Overview
ADO.NET provides a rich set of components for building data-driven applications on the Windows platform. It enables you to connect to relational databases, execute commands, and retrieve results efficiently.
Key Concepts
- Connection – Manages the link to a data source.
- Command – Executes SQL statements and stored procedures.
- DataReader – Provides fast, forward‑only access to query results.
- DataAdapter – Bridges the gap between DataSets and the database.
- Transactions – Ensure atomic operations.
Getting Started
Install the System.Data.SqlClient
NuGet package or use the built‑in library in .NET 6+.
dotnet add package System.Data.SqlClient
Sample code:
using System.Data.SqlClient;
string cs = "Server=.;Database=AdventureWorks;Trusted_Connection=True;";
using var conn = new SqlConnection(cs);
await conn.OpenAsync();
using var cmd = new SqlCommand("SELECT TOP 10 * FROM Production.Product", conn);
using var reader = await cmd.ExecuteReaderAsync();
while (await reader.ReadAsync())
{
Console.WriteLine($"{reader["ProductID"]}: {reader["Name"]}");
}
Best Practices
- Always use
using
statements orawait using
for connections and commands. - Prefer async APIs for scalability.
- Parameterize queries to prevent SQL injection.
- Leverage connection pooling (default behavior).
- Dispose of
SqlDataReader
promptly to free resources.