ADO.NET connections and commands
ADO.NET connections and commands
ADO.NET provides database access through connections, commands, readers and transactions. A connection manages access to a database, a command carries SQL and parameters, and a reader advances through result rows. Concrete implementations are supplied by a database provider. Here Microsoft.Data.Sqlite uses a local in-memory database that exists only while its connection is open.
Proposed baseline: .NET SDK 10.0.404, net10.0 / C# 14. Requires reviewed Microsoft.Data.Sqlite 10.0.15 candidate package and native dependencies. All databases are private in-memory fixtures; no network or disk database. C# results are reasoned, not executed. See the accompanying independent project fixture; approve dependencies and environment before restoring or building.
Create and query a local table
Open one connection, create a table, insert a synthetic row, and count the rows. No file or network is needed.
using System;using Microsoft.Data.Sqlite;using var db = new SqliteConnection("Data Source=:memory:;Pooling=False");db.Open();using var cmd = db.CreateCommand();cmd.CommandText = "CREATE TABLE Items (Id INTEGER PRIMARY KEY, Name TEXT NOT NULL)";cmd.ExecuteNonQuery();cmd.CommandText = "INSERT INTO Items VALUES (1, 'Pencil')";Console.WriteLine(cmd.ExecuteNonQuery());cmd.CommandText = "SELECT COUNT(*) FROM Items";Console.WriteLine(cmd.ExecuteScalar());ExecuteNonQuery returns affected-row count for this INSERT. ExecuteScalar returns the first column of the first row; COUNT returns a number even for an empty table.
Expected observation (reasoned, not executed):
11Read a result one row at a time
Explicit ORDER BY makes the expected output independent of physical row order.
using System;using Microsoft.Data.Sqlite;using var db = new SqliteConnection("Data Source=:memory:;Pooling=False");db.Open();using var cmd = db.CreateCommand();cmd.CommandText = "CREATE TABLE Items (Id INTEGER PRIMARY KEY, Name TEXT NOT NULL)";cmd.ExecuteNonQuery();cmd.CommandText = "INSERT INTO Items VALUES (2, 'Paper'), (1, 'Pen')";cmd.ExecuteNonQuery();cmd.CommandText = "SELECT Id, Name FROM Items ORDER BY Id";using var reader = cmd.ExecuteReader();while (reader.Read()) Console.WriteLine($"{reader.GetInt64(0)}: {reader.GetString(1)}");Read moves to the next row and returns false at the end. The reader is disposed before the command and connection because using declarations unwind in reverse order.
Expected observation (reasoned, not executed):
1: Pen2: PaperDistinguish empty result and SQL NULL
A scalar query with no rows differs from a row whose first column is SQL NULL.
using System;using Microsoft.Data.Sqlite;using var db = new SqliteConnection("Data Source=:memory:;Pooling=False");db.Open();using var cmd = db.CreateCommand();cmd.CommandText = "SELECT 1 WHERE 1 = 0";Console.WriteLine(cmd.ExecuteScalar() is null);cmd.CommandText = "SELECT NULL";Console.WriteLine(cmd.ExecuteScalar() is DBNull);No row produces a C# null reference; a SQL NULL result produces DBNull.Value in this provider. Do not cast either directly to a nonnullable number.
Expected observation (reasoned, not executed):
TrueTrueCommon mistakes and edge cases
Keep connections short-lived for ordinary pooled server access; dispose them promptly and never use the same connection concurrently unless explicitly supported. Pooling can reuse underlying physical connections, so closing a logical connection is not necessarily closing a socket. SQLite has no remote server in this example. Npgsql targets PostgreSQL and recommends positional parameters in modern releases; Microsoft.Data.SqlClient targets SQL Server and uses named parameters. Driver versions, types, isolation and cancellation differ; these examples test neither server. Microsoft.Data.Sqlite async ADO.NET methods execute synchronously, unlike providers that implement actual asynchronous I/O. Use a provider-appropriate timeout and cancellation strategy; do not assume Async in a method name guarantees nonblocking I/O.
Practice and recap
Plan a local query listing item names in ascending ID order. Specify which method creates the command, which runs the query, which advances rows and in what order resources close. Include an empty table case.
Hint: Use a reader for multiple rows.
Learning objective: Describe connection, command and reader lifetimes. See accompanying manual practice and knowledge check.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
ADO.NET connections and commands — knowledge check
Apply the lesson concepts to the following scenarios.
Which method returns a reader?
What does Read return when there are no more rows?
Which query guarantees ascending IDs?
What is true of pooling?
What is special about Microsoft.Data.Sqlite async methods?