The Analogy: Speaking the Language Without an Interpreter
Two people can do business through an interpreter. It is comfortable, it is fast enough, and the interpreter smooths over a hundred small differences in phrasing. But the interpreter is a layer: they decide how your sentence is rendered, and occasionally they render it in a way you would not have chosen. Sometimes you need to say the exact words yourself.
ADO.NET is speaking the language yourself. You write the SQL, you name the parameters, you read the columns back in order. There is no translation step deciding what your query looks like, which means there is nothing between your intent and the statement that reaches the server — and equally, nothing catching your mistakes. Entity Framework Core, covered in the next two lessons, is the interpreter; it is built on top of ADO.NET and hands the same objects to the same drivers underneath.
Learning the direct conversation first is not academic. Every connection string, every timeout, every pooled connection, every DbCommand that EF Core builds for you is an ADO.NET object. When a query is slow, when a transaction deadlocks, when a bulk import needs to be ten times faster than the ORM manages, you drop to this layer — and if you have never seen it, the drop feels like falling.
There is one rule in this lesson that is not stylistic. A SQL statement built by gluing user input into a string is the single most exploited defect in the history of web applications: the input '; DROP TABLE Orders; -- stops being data and becomes a command. Parameters exist so that values travel to the server as values, separately from the statement text, where no amount of quoting or punctuation can turn them back into SQL. Use them for every single value, every time.
Syntax or Core Structure
Four objects do all the work: a connection to the server, a command carrying statement text and parameters, a reader streaming rows back, and a transaction grouping writes. The examples use Microsoft.Data.Sqlite with an in-memory database so they run with no server to install, but the shapes are identical for Microsoft.Data.SqlClient and Npgsql:
dotnet add package Microsoft.Data.Sqlite
using System;
using Microsoft.Data.Sqlite;
class Program
{
static void Main()
{
using var conn = new SqliteConnection("Data Source=:memory:");
conn.Open();
using (var create = conn.CreateCommand())
{
create.CommandText = @"
CREATE TABLE Orders (
Id INTEGER PRIMARY KEY,
Customer TEXT NOT NULL,
Total REAL NOT NULL
);";
create.ExecuteNonQuery();
}
var rows = new (int Id, string Customer, double Total)[]
{
(1, "Acme Tools", 240.50),
(2, "Borealis", 99.00),
(3, "Acme Tools", 12.25)
};
// One command, three parameters, reused for every row.
using (var insert = conn.CreateCommand())
{
insert.CommandText =
"INSERT INTO Orders (Id, Customer, Total) VALUES (@id, @customer, @total);";
var id = insert.Parameters.Add("@id", SqliteType.Integer);
var customer = insert.Parameters.Add("@customer", SqliteType.Text);
var total = insert.Parameters.Add("@total", SqliteType.Real);
foreach (var row in rows)
{
id.Value = row.Id;
customer.Value = row.Customer;
total.Value = row.Total;
insert.ExecuteNonQuery();
}
}
// ExecuteReader: a forward-only stream of rows.
using (var query = conn.CreateCommand())
{
query.CommandText = @"
SELECT Customer, COUNT(*) AS Orders, SUM(Total) AS Revenue
FROM Orders
GROUP BY Customer
ORDER BY Customer;";
using var reader = query.ExecuteReader();
while (reader.Read())
{
string name = reader.GetString(0);
int count = reader.GetInt32(1);
double revenue = reader.GetDouble(2);
Console.WriteLine(name.PadRight(12) + count + " " + revenue.ToString("0.00"));
}
}
// ExecuteScalar: the first column of the first row.
using (var scalar = conn.CreateCommand())
{
scalar.CommandText = "SELECT COUNT(*) FROM Orders WHERE Total > @min;";
scalar.Parameters.AddWithValue("@min", 50.0);
long big = (long)scalar.ExecuteScalar()!;
Console.WriteLine("over 50: " + big);
}
}
}
Output:
Acme Tools 2 252.75
Borealis 1 99.00
over 50: 2
The three Execute methods are the whole API surface for running a statement, and choosing the right one matters. ExecuteNonQuery returns the number of affected rows — which is not a formality: a conditional UPDATE returning 0 is how you detect "the row was not in the state I expected", a technique the Real World Example leans on. ExecuteScalar returns the first column of the first row as object?, so it needs a cast and a null check. ExecuteReader returns a cursor that holds resources on the server until disposed, which is why every one of them is wrapped in using.
Two details in the insert loop are deliberate. The command and its parameters are created once and only the .Value properties change per row, which lets the provider reuse the prepared statement instead of re-parsing identical SQL three times. And Parameters.Add(name, type) states the database type explicitly rather than letting AddWithValue infer it — inference is convenient and occasionally guesses a type that defeats an index, so the explicit form is the better habit for anything on a hot path.
Technical Depth: The Provider Model, Pooling and Transactions
One shape, many databases
ADO.NET is a set of abstract base classes in System.Data.Common; each database ships a provider that subclasses them. Code written against the base types works against any provider.
| Abstract type | SQL Server | PostgreSQL | SQLite |
|---|---|---|---|
DbConnection | SqlConnection | NpgsqlConnection | SqliteConnection |
DbCommand | SqlCommand | NpgsqlCommand | SqliteCommand |
DbDataReader | SqlDataReader | NpgsqlDataReader | SqliteDataReader |
DbTransaction | SqlTransaction | NpgsqlTransaction | SqliteTransaction |
| NuGet package | Microsoft.Data.SqlClient | Npgsql | Microsoft.Data.Sqlite |
What is not portable is the SQL itself and the parameter prefix: SQL Server uses @name, PostgreSQL accepts @name or :name, Oracle uses :name. Writing against DbConnection gives you a swappable driver, not a swappable dialect.
Connections are pooled, so open late and close early
conn.Open() on a pooled provider does not usually open a socket; it takes a live connection from a pool keyed by the exact connection string. Dispose() returns it to the pool rather than closing it. The consequences are counter-intuitive if you come from other platforms:
- Do create a connection, use it, and dispose it inside the smallest scope that needs it. That is the cheap path.
- Do not hold a connection open in a singleton or a static field for the lifetime of the application. One field means one connection for all requests, which serialises the entire application onto a single database session.
- Do not build connection strings dynamically with tiny variations. Each distinct string gets its own pool, so a per-tenant string with a different
Application Namemultiplies your pools. - Pool exhaustion presents as a timeout on
Open(), not on the query, and the usual cause is a leaked reader or a missingusingsomewhere else entirely.
Reading rows without paying for it twice
DbDataReader is forward-only and one row at a time. The typed getters take an ordinal, not a name, and reader["Customer"] does a lookup plus a boxing conversion on every access. In a loop over a hundred thousand rows that is measurable, so resolve ordinals once before the loop:
using var reader = cmd.ExecuteReader();
int iId = reader.GetOrdinal("Id");
int iShipped = reader.GetOrdinal("ShippedOn");
while (reader.Read())
{
long id = reader.GetInt64(iId);
DateTime? shipped = reader.IsDBNull(iShipped)
? null
: reader.GetDateTime(iShipped);
}
Nulls are the trap. A database NULL arrives as DBNull.Value, which is an object, not null — so reader.GetString(i) on a null column throws InvalidCastException rather than returning null. Every nullable column needs an IsDBNull check first, or GetFieldValue<T?>(i) which handles it for you. Going the other way, a parameter whose value should be NULL must be set to DBNull.Value; assigning C# null to parameter.Value means "no value supplied" and typically raises an error about a missing parameter.
Async is not optional for server code
Every blocking method has an async twin: OpenAsync, ExecuteNonQueryAsync, ExecuteReaderAsync, ReadAsync, and DisposeAsync via await using. A database call spends nearly all of its time waiting on the network, and the synchronous versions hold a thread-pool thread for that entire wait. Under load that is the difference between a server that queues and one that stalls. Use the async form everywhere except in a console entry point or a one-off script.
Transactions
BeginTransaction returns a DbTransaction; every command that should take part must have its Transaction property set to it, and providers such as SQLite throw if you run a command on the connection without doing so. Dispose without Commit performs a rollback, so a using block is already a safety net.
| Isolation level | Prevents | Cost |
|---|---|---|
ReadUncommitted | Nothing; may read uncommitted rows | Lowest |
ReadCommitted | Dirty reads (the usual default) | Low |
RepeatableRead | Rows changing under you mid-transaction | Higher, more locks |
Serializable | Phantom rows; behaves as if transactions ran one by one | Highest |
Snapshot | Readers blocking writers, via row versions | Extra version storage |
Hold transactions for as short a time as possible and never across a call to something slow — an HTTP request inside a transaction holds database locks for the duration of somebody else's outage.
Real World Example: A Ledger That Must Balance
Money movement is the case where "mostly correct" is worthless. A transfer must debit one account and credit another as a single indivisible step, must never let a balance go negative, and must leave an audit row behind. The interesting part is that two of those three guarantees come from SQL, not from C#: the negative-balance check is a condition in the UPDATE, and the indivisibility is the transaction.
using System;
using Microsoft.Data.Sqlite;
sealed class Bank
{
private readonly SqliteConnection conn;
public Bank(SqliteConnection conn) => this.conn = conn;
// Money is stored as integer minor units - never as a floating-point amount.
public long Balance(string account)
{
using var cmd = conn.CreateCommand();
cmd.CommandText = "SELECT Cents FROM Accounts WHERE Id = @id;";
cmd.Parameters.AddWithValue("@id", account);
object? value = cmd.ExecuteScalar(); // null means no such row
if (value is null)
throw new InvalidOperationException("unknown account " + account);
return (long)value;
}
public long LedgerCount()
{
using var cmd = conn.CreateCommand();
cmd.CommandText = "SELECT COUNT(*) FROM Ledger;";
return (long)cmd.ExecuteScalar()!;
}
public bool Transfer(string from, string to, long cents)
{
using var tx = conn.BeginTransaction();
// The guard is in the WHERE clause: 0 rows affected means the funds
// were not there when the statement ran. No read-then-write race.
int debited = Execute(tx,
"UPDATE Accounts SET Cents = Cents - @amt WHERE Id = @id AND Cents >= @amt;",
from, cents);
if (debited == 0)
{
tx.Rollback();
return false;
}
int credited = Execute(tx,
"UPDATE Accounts SET Cents = Cents + @amt WHERE Id = @id;",
to, cents);
if (credited == 0)
{
tx.Rollback(); // undoes the debit above as well
throw new InvalidOperationException("unknown account " + to);
}
using (var log = conn.CreateCommand())
{
log.Transaction = tx;
log.CommandText =
"INSERT INTO Ledger (FromId, ToId, Cents) VALUES (@from, @to, @amt);";
log.Parameters.AddWithValue("@from", from);
log.Parameters.AddWithValue("@to", to);
log.Parameters.AddWithValue("@amt", cents);
log.ExecuteNonQuery();
}
tx.Commit();
return true;
}
private int Execute(SqliteTransaction tx, string sql, string account, long cents)
{
using var cmd = conn.CreateCommand();
cmd.Transaction = tx; // required: the command joins the transaction
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("@id", account);
cmd.Parameters.AddWithValue("@amt", cents);
return cmd.ExecuteNonQuery(); // rows affected
}
}
class Program
{
static void Main()
{
using var conn = new SqliteConnection("Data Source=:memory:");
conn.Open();
using (var setup = conn.CreateCommand())
{
setup.CommandText = @"
CREATE TABLE Accounts (
Id TEXT PRIMARY KEY,
Cents INTEGER NOT NULL CHECK (Cents >= 0)
);
CREATE TABLE Ledger (
Id INTEGER PRIMARY KEY AUTOINCREMENT,
FromId TEXT NOT NULL,
ToId TEXT NOT NULL,
Cents INTEGER NOT NULL
);
INSERT INTO Accounts (Id, Cents) VALUES ('A-100', 50000), ('B-200', 12000);";
setup.ExecuteNonQuery();
}
var bank = new Bank(conn);
Console.WriteLine("start: " + Snapshot(bank));
Attempt(bank, "A-100", "B-200", 20000);
Console.WriteLine("after: " + Snapshot(bank));
Attempt(bank, "A-100", "B-200", 90000);
Console.WriteLine("after: " + Snapshot(bank));
Attempt(bank, "A-100", "Z-999", 5000);
Console.WriteLine("final: " + Snapshot(bank));
Console.WriteLine("ledger: " + bank.LedgerCount() + " row(s)");
}
static void Attempt(Bank bank, string from, string to, long cents)
{
string label = "transfer: " + Money(cents).PadRight(8);
try
{
Console.WriteLine(label + (bank.Transfer(from, to, cents) ? "committed" : "rejected"));
}
catch (InvalidOperationException ex)
{
Console.WriteLine(label + "failed: " + ex.Message);
}
}
static string Snapshot(Bank bank) =>
"A-100=" + Money(bank.Balance("A-100")) + " B-200=" + Money(bank.Balance("B-200"));
static string Money(long cents) => (cents / 100m).ToString("0.00");
}
Output:
start: A-100=500.00 B-200=120.00
transfer: 200.00 committed
after: A-100=300.00 B-200=320.00
transfer: 900.00 rejected
after: A-100=300.00 B-200=320.00
transfer: 50.00 failed: unknown account Z-999
final: A-100=300.00 B-200=320.00
ledger: 1 row(s)
The rejected transfer is the interesting one. There is no if (Balance(from) >= cents) anywhere in this code, and that absence is the design. A read-then-write check has a window between the read and the write in which another request can spend the same money — the classic race that produces an overdrawn account and an unreproducible bug report. Putting AND Cents >= @amt in the UPDATE moves the decision inside the database's own atomic statement: either the row matched and the money moved, or it did not match and ExecuteNonQuery returned 0. Two concurrent transfers of 400.00 from a 500.00 balance cannot both succeed, whatever the timing.
The failed transfer proves the transaction. The debit to A-100 ran successfully and affected one row; then the credit to Z-999 matched nothing, and the rollback took the debit with it. final: shows A-100=300.00, exactly what it was before the attempt — 50.00 did not evaporate. Had the same code committed each statement separately, the money would now be gone from one account and present in none, and the only record would be a support ticket.
The ledger count of 1 closes the loop. Three attempts were made and exactly one produced an audit row, because the INSERT sat inside the same transaction as the two UPDATEs. This is the property that makes an audit table trustworthy: it cannot record a transfer that did not happen, and it cannot miss one that did. An audit row written outside the transaction — or worse, written by a separate service after the fact — has neither guarantee.
Two smaller decisions carry their weight. Balances are INTEGER cents rather than a floating-point amount, because 0.1 + 0.2 is not 0.3 in binary floating point and a ledger that drifts by fractions of a cent is a ledger nobody trusts; decimal is the other correct answer, but integers are exact everywhere including in SQL. And the CHECK (Cents >= 0) constraint is a second line of defence: even if a future developer writes an UPDATE without the guard, the database itself refuses the row.
Common Mistakes
- Building SQL by concatenating values.
"SELECT * FROM Users WHERE Name = '" + name + "'"is an injection vulnerability, full stop. An input ofx' OR '1'='1returns every row; worse inputs run statements you never wrote. Interpolated strings andstring.Formatare exactly as dangerous as+. Parameters are the only fix — escaping quotes by hand is not. - Forgetting
usingon a reader or connection. A leakedDbDataReaderholds a server-side cursor and keeps its connection out of the pool. The symptom appears minutes later as a timeout onOpen()in a completely unrelated request, which is why these bugs are so hard to trace back. - Calling
GetStringon a nullable column. ANULLarrives asDBNull.Value, so the typed getter throwsInvalidCastExceptioninstead of returningnull. CheckIsDBNull(ordinal)first, or useGetFieldValue<T?>(ordinal). - Passing C#
nullas a parameter value.cmd.Parameters.AddWithValue("@note", null)does not mean "insert NULL"; it usually means "this parameter has no value" and the provider errors out. Use(object?)note ?? DBNull.Value. - Running a command inside a transaction without setting
cmd.Transaction. Some providers silently run it outside the transaction; SQLite and SqlClient throw. Either way the statement is not covered by the rollback you think protects it. - Checking a condition in C# and then writing.
if (Balance(id) >= amount) Debit(id, amount);has a race window between the two statements. Push the condition into theWHEREclause and inspect the affected-row count instead. - Holding one connection in a static field. It works on your machine and serialises every request in production. Connections are pooled precisely so that creating one per unit of work is the cheap option.
- Using the synchronous methods in a web request.
ExecuteReaderblocks a thread-pool thread for the whole round trip. At low traffic nobody notices; at high traffic the pool starves and latency goes vertical while the CPU sits idle.
Best Practices
- Parameterise every value with no exceptions, and keep statement text as a constant string so that reviewers can see at a glance that no input is glued into it.
- Wrap connections, commands, readers and transactions in
using(orawait using) declarations so disposal cannot be skipped by an early return or an exception. - Prefer the async methods throughout server code, and pass a
CancellationTokenso an abandoned request stops waiting on the database. - Create a connection per unit of work and dispose it promptly; let the pool handle the expensive part.
- Express invariants in the database as well as in code:
NOT NULL,CHECK, unique indexes and foreign keys catch the bug that slips past yourif. - Detect lost updates by making writes conditional and inspecting the affected-row count, rather than reading first and hoping nothing changed in between.
- Store money as integer minor units or
decimal, never asdouble, and keep the same representation in the database, the C# model and the API. - Resolve reader ordinals once before the loop, and choose
ExecuteScalarorExecuteNonQuerywhen you do not need rows, so you are not paying for a cursor you never read.
Practice Exercises
- See the injection, then close it. Build a SQLite table of products and write a lookup that concatenates a search term into the SQL. Pass
x' OR '1'='1and watch every row come back. Now convert it to a parameterised query and confirm the same input returns zero rows because it is treated as a literal name. - Make a nullable column safe. Add a nullable
ShippedOn TEXTcolumn to theOrderstable, insert one row with a value and one without, then write a reader loop that prints"pending"for the null case. First write it withGetStringand observe the exception, then fix it withIsDBNull, and finally insert a third row passingDBNull.Valueexplicitly from C#. - Prove the rollback. Extend the
Bankexample with aTransferBatchmethod that takes several transfers and applies them all inside one transaction, throwing if any single one is rejected. Verify that a batch of three where the second is unaffordable leaves every balance and theLedgertable exactly as they started. - Measure the cost of doing it slowly. Insert fifty thousand rows two ways: one
INSERTper row with its own connection and no transaction, then the same rows through a single reused command inside one transaction. Time both withStopwatch, then add a third run using the async methods, and write down the ratio between them.