ADO.NET Basics
Beginner
20 min read
Lesson 2 of 5
ADO.NET is the core .NET library for talking to databases. First, add the NuGet package:
Install-Package Microsoft.Data.SqlClient
The core objects
- SqlConnection — represents the connection to the database.
- SqlCommand — represents a SQL statement or stored procedure call.
- SqlParameter — a safely-typed value passed into a command (prevents SQL injection).
- SqlDataReader — reads results row-by-row, forward-only.
A minimal read example
using Microsoft.Data.SqlClient;
string connectionString = "Server=localhost\\SQLEXPRESS;Database=SchoolDB;Trusted_Connection=True;TrustServerCertificate=True;";
using var connection = new SqlConnection(connectionString);
connection.Open();
using var command = new SqlCommand("SELECT StudentId, FirstName, LastName FROM Students", connection);
using var reader = command.ExecuteReader();
while (reader.Read())
{
int id = reader.GetInt32(0);
string firstName = reader.GetString(1);
string lastName = reader.GetString(2);
Console.WriteLine($"{id}: {firstName} {lastName}");
}
Why "using"?
SqlConnection, SqlCommand, and SqlDataReader
all hold unmanaged resources. The using keyword guarantees
they're closed and disposed even if an exception occurs.
Key Takeaway
ADO.NET is the foundation of database access in C#. Always use using blocks to properly dispose database resources.