Getting Started with ADO.NET
ADO.NET provides a rich set of components for building data-driven applications on the .NET platform. This guide walks you through creating a simple console app that connects to a SQL Server database, executes a query, and reads the results.
Prerequisites
- Visual Studio 2022 or later
- .NET 6.0 SDK (or later)
- SQL Server Express (or any accessible SQL Server instance)
1. Create a .NET Console Project
dotnet new console -n AdoNetDemo
cd AdoNetDemo
dotnet add package System.Data.SqlClient
dotnet run
2. Establish a Connection
using System;
using System.Data.SqlClient;
class Program
{
static void Main()
{
var connectionString = "Server=localhost;Database=Northwind;Trusted_Connection=True;";
using var connection = new SqlConnection(connectionString);
try
{
connection.Open();
Console.WriteLine("Connection successful!");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
3. Execute a Query with SqlCommand
string query = "SELECT TOP 5 ProductName, UnitPrice FROM Products ORDER BY UnitPrice DESC;";
using var command = new SqlCommand(query, connection);
using var reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine($"{reader["ProductName"]} - ${reader["UnitPrice"]:0.00}");
}
Full Sample Code
using System;
using System.Data.SqlClient;
class Program
{
static void Main()
{
var connectionString = "Server=localhost;Database=Northwind;Trusted_Connection=True;";
using var connection = new SqlConnection(connectionString);
connection.Open();
string query = "SELECT TOP 5 ProductName, UnitPrice FROM Products ORDER BY UnitPrice DESC;";
using var command = new SqlCommand(query, connection);
using var reader = command.ExecuteReader();
Console.WriteLine("Top 5 most expensive products:");
while (reader.Read())
{
Console.WriteLine($"{reader["ProductName"]} - ${reader["UnitPrice"]:0.00}");
}
}
}
Next Steps
- Explore SqlDataReader for forward-only streaming.
- Use DataSet and SqlDataAdapter for disconnected scenarios.
- Implement parameterized queries to prevent SQL injection.
- Learn about asynchronous APIs in the Async Programming Guide.