C# & ADO.NET

ADO.NET data access in C#: readers, scalars, DataSets, DataTables, TVPs and bulk loads

C# & ADO.NET · · Published 2026-11-29

ADO.NET is a small set of classes with clearly separated jobs. A SqlCommand runs SQL; depending on what you expect back, you call ExecuteReader (rows), ExecuteScalar (one value) or ExecuteNonQuery (a count of affected rows). Rows can be streamed with a DataReader or kept in memory in a DataTable or DataSet. Large writes go through table-valued parameters or SqlBulkCopy. This guide walks through each of these with SQL Server, always with parameters and using blocks, so that the examples can be pasted into real code.

Which API for which result

You expect…CallSection
Rows to display onceExecuteReaderExecuteReader
A single value (count, total, new id)ExecuteScalarExecuteScalar
Nothing back but a row countExecuteNonQueryExecuteNonQuery example
Data to keep after the connection closesDataTable, DataSet, DataTable.LoadDataSet vs DataTable
Hundreds of rows to send to a procedureTable-valued parameterTVPs
Thousands of rows from a fileSqlBulkCopyBulk import

The three Execute… methods are compared side by side in ExecuteReader vs ExecuteNonQuery vs ExecuteScalar.

Reading rows with ExecuteReader

The fastest way to read: a forward-only stream of rows from an open connection.

ExecuteReader returns a SqlDataReader: a fast, forward-only stream of rows. You call Read() until it returns false and pick values from each row. This example reads a list of upcoming events, then shows two extras: several result sets in one round trip and a single-row lookup.

Reading rows into a list

public class EventItem
{
    public int Id { get; set; }
    public string Title { get; set; }
    public DateTime StartsAt { get; set; }
    public string Venue { get; set; } // nullable column
}

public static List<EventItem> GetUpcoming(string cs, int max)
{
    const string sql = @"SELECT TOP (@max) EventId, Title, StartsAt, Venue
                         FROM dbo.Events
                         WHERE StartsAt >= SYSUTCDATETIME()
                         ORDER BY StartsAt";
    var list = new List<EventItem>();
    using (var con = new SqlConnection(cs))
    using (var cmd = new SqlCommand(sql, con))
    {
        cmd.Parameters.Add("@max", SqlDbType.Int).Value = max;
        con.Open();
        using (SqlDataReader r = cmd.ExecuteReader())
        {
            while (r.Read())
            {
                list.Add(new EventItem
                {
                    Id = r.GetInt32(0),
                    Title = r.GetString(1),
                    StartsAt = r.GetDateTime(2),
                    Venue = r.IsDBNull(3) ? null : r.GetString(3)
                });
            }
        }
    }
    return list;
}

Typed getters (GetInt32, GetString…) must match the column's SQL type; reading an int column with GetInt64 throws InvalidCastException. Check IsDBNull first on every nullable column.

Showing the result on the page

<asp:Repeater ID="rptEvents" runat="server" ItemType="Demo.EventItem">
    <HeaderTemplate><ul class="events"></HeaderTemplate>
    <ItemTemplate>
        <li><time datetime='<%# Item.StartsAt.ToString("s") %>Z'><%# Item.StartsAt.ToString("d MMM yyyy HH:mm") %></time>
            <%#: Item.Title %> <%#: Item.Venue ?? "" %></li>
    </ItemTemplate>
    <FooterTemplate></ul></FooterTemplate>
</asp:Repeater>
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        rptEvents.DataSource = GetUpcoming(ConfigurationManager.ConnectionStrings["Db"].ConnectionString, 10);
        rptEvents.DataBind();
    }
}

<%#: … %> encodes the text, so a title containing <script> is shown, not executed. Never build HTML by concatenating reader values without encoding.

Several result sets in one call

const string sql = @"SELECT COUNT(*) FROM dbo.Events WHERE StartsAt >= SYSUTCDATETIME();
                     SELECT TOP (5) Title FROM dbo.Events ORDER BY CreatedAt DESC;";
using (var con = new SqlConnection(cs))
using (var cmd = new SqlCommand(sql, con))
{
    con.Open();
    using (SqlDataReader r = cmd.ExecuteReader())
    {
        r.Read();
        int upcoming = r.GetInt32(0);

        r.NextResult();                  // move to the second SELECT
        var latest = new List<string>();
        while (r.Read()) latest.Add(r.GetString(0));
    }
}

One row only

using (SqlDataReader r = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
    if (r.Read())
    {
        // found
    }
}

CommandBehavior.SingleRow tells the provider you expect at most one row, which can save work. Other useful flags: CloseConnection (closing the reader closes the connection) and SequentialAccess (for large binary or text columns read as streams, in column order).

Things to avoid

Binding a reader straight to a grid is shown in Bind a GridView with ExecuteReader; turning it into a table in Convert a SqlDataReader to a DataTable.

Reading one value with ExecuteScalar

When the answer is a single value, a reader is overkill.

ExecuteScalar returns the first column of the first row of a query, as an object. It is the right tool when the answer is a single value: a count, a total, a flag, a name, a new id. The only care it needs is converting that object correctly.

A small helper

public static class Db
{
    private static string Cs => ConfigurationManager.ConnectionStrings["Db"].ConnectionString;

    public static object Scalar(string sql, params SqlParameter[] parameters)
    {
        using (var con = new SqlConnection(Cs))
        using (var cmd = new SqlCommand(sql, con))
        {
            cmd.Parameters.AddRange(parameters);
            con.Open();
            return cmd.ExecuteScalar();
        }
    }
}

Counting rows

int open = (int)Db.Scalar(
    "SELECT COUNT(*) FROM dbo.Tickets WHERE Status = @s",
    new SqlParameter("@s", SqlDbType.VarChar, 10) { Value = "open" });

lblOpen.Text = open + " open ticket(s)";

COUNT(*) returns int, so the cast is safe. COUNT_BIG(*) would return long.

Is this user name taken?

protected void cvUserName_ServerValidate(object source, ServerValidateEventArgs args)
{
    object found = Db.Scalar(
        "SELECT 1 FROM dbo.Users WHERE UserName = @u",
        new SqlParameter("@u", SqlDbType.NVarChar, 50) { Value = args.Value.Trim() });

    args.IsValid = found == null; // no row: the name is free
}

Used from a CustomValidator, this check runs on the server during validation. It improves the user experience, but two users can still pick the same name at the same moment: a unique index on UserName remains the real guarantee.

Null and DBNull

object v = Db.Scalar("SELECT MAX(Amount) FROM dbo.Payments WHERE CustomerId = @c",
    new SqlParameter("@c", SqlDbType.Int) { Value = customerId });

// MAX over zero rows returns one row containing NULL -> DBNull.Value
decimal? largest = v is DBNull || v == null ? (decimal?)null : (decimal)v;
Query resultExecuteScalar returns
No rowsnull
A row whose first column is NULL (e.g. aggregate over no rows)DBNull.Value
A valueThe value, boxed in its .NET type (int, decimal, string, DateTime…)

Casting DBNull.Value or null to a value type throws. Convert.ToInt32(DBNull.Value) also throws, while Convert.ToInt32(null) returns 0, which can hide a missing row; be explicit.

Returning the id of a new row

int newId = (int)Db.Scalar(
    @"INSERT INTO dbo.Tickets (Subject, Status) OUTPUT INSERTED.TicketId VALUES (@subject, 'open');",
    new SqlParameter("@subject", SqlDbType.NVarChar, 200) { Value = txtSubject.Text.Trim() });

Response.Redirect("Ticket.aspx?id=" + newId, false);
Context.ApplicationInstance.CompleteRequest();

OUTPUT INSERTED.TicketId returns the value with the column's own type (int). If the table has triggers, use SELECT CAST(SCOPE_IDENTITY() AS int) after the insert instead, because OUTPUT without INTO is not allowed on tables with enabled triggers.

When not to use it

If you need two values, return them as two columns and use a reader, or use output parameters; calling ExecuteScalar twice doubles the round trips. And do not run a query returning many rows just to take the first cell: write TOP (1) or an aggregate so the server does less work. The full comparison is in ExecuteReader vs ExecuteNonQuery vs ExecuteScalar.

DataSet vs DataTable

When the data must outlive the connection, it goes into memory, in a table or a set of tables.

A DataTable is one in-memory table: columns, rows, constraints. A DataSet is a container of DataTables plus the relations between them. Both are disconnected: once filled, they no longer need the database connection.

Side by side

DataTableDataSet
HoldsOne tableA collection of tables (Tables) and Relations
Typical filladapter.Fill(table) or table.Load(reader)adapter.Fill(dataSet), one table per result set
RelationsNoYes, with parent/child navigation and cascading constraints
XMLWriteXml/ReadXml (needs a table name)WriteXml/ReadXml with schema
OverheadLowerHigher

Filling a DataTable

var customers = new DataTable("Customers");
using (var con = new SqlConnection(cs))
using (var da = new SqlDataAdapter("SELECT CustomerId, Name, Country FROM dbo.Customers", con))
{
    da.Fill(customers);  // opens and closes the connection itself
}
foreach (DataRow row in customers.Rows)
{
    string name = row.Field<string>("Name");   // System.Data.DataSetExtensions
}

A DataSet with a relation

var ds = new DataSet();
using (var con = new SqlConnection(cs))
using (var cmd = new SqlCommand(
    "SELECT CustomerId, Name FROM dbo.Customers; SELECT OrderId, CustomerId, Total FROM dbo.Orders;", con))
using (var da = new SqlDataAdapter(cmd))
{
    da.TableMappings.Add("Table", "Customers");
    da.TableMappings.Add("Table1", "Orders");
    da.Fill(ds);
}
ds.Relations.Add("CustomerOrders",
    ds.Tables["Customers"].Columns["CustomerId"],
    ds.Tables["Orders"].Columns["CustomerId"]);

foreach (DataRow c in ds.Tables["Customers"].Rows)
{
    DataRow[] orders = c.GetChildRows("CustomerOrders");
}

Without table mappings, the tables are named Table, Table1 and so on, in result-set order. Adding the relation also creates a foreign-key constraint: an order whose customer is missing makes Relations.Add throw.

When to use which

Both are heavy in session state and view state; store keys rather than whole tables where you can.

Typed DataSets and alternatives

Visual Studio's DataSet designer generates typed DataSets with a class per table and properties per column, plus TableAdapters that hold the SQL. They remove string column names from code and are common in Web Forms projects from the 2005–2012 era. They are still supported on .NET Framework but receive no new features. When maintaining such a project, keep using them consistently; when writing new data access, plain classes with ADO.NET, Dapper or Entity Framework are easier to test and to move to modern .NET.

DataReader, DataAdapter, DataSet and DataView: who does what

The four classes interviewers list together are stages of one pipeline, not alternatives.

These four classes are often listed together in interviews as if they were alternatives. They are not: they play different roles in the same pipeline. A DataReader streams rows from an open connection; a DataAdapter uses commands to fill a DataSet and to save its changes; a DataSet (with its DataTables) holds the data in memory; a DataView presents a DataTable filtered and sorted.

Roles at a glance

ClassConnected?Role
SqlDataReaderYes, needs an open connectionRead rows once, forward only, read only, fast
SqlDataAdapterOpens and closes the connection as neededBridge: Fill from the database, Update back to it
DataSet / DataTableNoIn-memory tables, rows, relations, change tracking
DataViewNoA filtered, sorted view over one DataTable, bindable to controls

DataReader: stream and forget

using (var con = new SqlConnection(cs))
using (var cmd = new SqlCommand("SELECT Name, Price FROM dbo.Products", con))
{
    con.Open();
    using (SqlDataReader r = cmd.ExecuteReader())
    {
        while (r.Read())
        {
            Console.WriteLine(r.GetString(0) + ": " + r.GetDecimal(1));
        }
    }
}

Lowest memory use and fastest for display or processing in one pass. You cannot go back, count rows in advance or keep the reader after the connection closes. Examples: ExecuteReader example.

DataAdapter and DataSet: work disconnected

var ds = new DataSet();
using (var con = new SqlConnection(cs))
using (var da = new SqlDataAdapter("SELECT ProductId, Name, Price FROM dbo.Products", con))
{
    da.Fill(ds, "Products");          // opens, reads everything, closes

    DataTable t = ds.Tables["Products"];
    t.Rows[0]["Price"] = 9.99m;       // change tracked in memory (RowState = Modified)

    var builder = new SqlCommandBuilder(da); // generates UPDATE/INSERT/DELETE from the SELECT
    da.Update(t);                     // sends only the changed rows
}

SqlCommandBuilder works for single-table queries that include the primary key. For anything more complex, set da.UpdateCommand, InsertCommand and DeleteCommand yourself with parameters. The difference between a DataSet and a single DataTable is covered in DataSet vs DataTable.

DataView: filter and sort without a new query

DataTable products = ds.Tables["Products"];
var view = new DataView(products)
{
    RowFilter = "Price < 20 AND Name LIKE 'A%'",
    Sort = "Price DESC"
};
gvCheap.DataSource = view;
gvCheap.DataBind();

DataTable copy = view.ToTable();   // materialise the view as a new table

RowFilter uses its own expression syntax, documented under DataColumn.Expression; it is not SQL. If the filter contains user input, escape single quotes by doubling them, or better, filter with LINQ to DataSet (products.AsEnumerable().Where(...)). Every DataTable has a DefaultView, which is what a grid binds to when you pass it the table.

Choosing

From a reader to a DataTable with DataTable.Load

Between the two worlds sits a one-line bridge.

You have a SqlDataReader but need a DataTable: to bind a paging GridView, to keep the data after the connection closes, or to pass it to a method that expects a table. DataTable.Load does the conversion in one call.

Basic usage

public static DataTable Query(string cs, string sql, params SqlParameter[] parameters)
{
    var table = new DataTable();
    using (var con = new SqlConnection(cs))
    using (var cmd = new SqlCommand(sql, con))
    {
        cmd.Parameters.AddRange(parameters);
        con.Open();
        using (SqlDataReader reader = cmd.ExecuteReader())
        {
            table.Load(reader);  // builds the columns from the reader's schema, copies all rows
        }
    }
    return table;               // usable after the connection is closed
}

DataTable orders = Query(cs,
    "SELECT OrderId, Customer, Total FROM dbo.Orders WHERE OrderDate >= @from",
    new SqlParameter("@from", SqlDbType.Date) { Value = DateTime.Today.AddDays(-30) });

Load reads the reader to the end of the current result set. If the reader has more result sets, it moves to the next one; if not, it closes the reader. That is why loading several tables in a row works:

using (SqlDataReader r = cmd.ExecuteReader())  // "SELECT ... ; SELECT ... ;"
{
    var customers = new DataTable("Customers");
    var orders = new DataTable("Orders");
    customers.Load(r);   // first result set, then advances
    orders.Load(r);      // second result set
}

A DataSet has a matching method: ds.Load(reader, LoadOption.OverwriteChanges, "Customers", "Orders").

Columns, keys and constraint errors

Load creates columns with the reader's names and .NET types. It also reads key information from the schema, so a query that returns duplicate values in a primary-key column (for example through a join) can fail with "Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints." Fixes:

LoadOption

When the table already contains rows with the same primary key, the LoadOption argument decides what happens: PreserveChanges (the default) keeps pending edits, OverwriteChanges replaces current and original values, Upsert updates current values only. For a fresh table, the option has no visible effect.

Load or SqlDataAdapter.Fill?

DataTable.Load(reader)adapter.Fill(table)
Who opens the connectionYouThe adapter, if closed
Already have a readerIdealNot applicable
Saving changes backConfigure an adapter separatelySame adapter's Update
Paging overloadsNoFill(startRecord, maxRecords, …)

Both end with the same kind of table; pick the one that fits the code you already have. The roles of these classes are compared in DataSet, DataReader, DataAdapter and DataView, and binding the result in Bind a GridView with ExecuteReader.

Sending many rows at once: table-valued parameters

Writing is the other half of data access. For a batch of rows, one call beats hundreds.

Inserting 500 order lines one INSERT at a time means 500 round trips. A table-valued parameter (TVP) sends all of them in a single call, as a parameter shaped like a table. SQL Server has supported TVPs since 2008; ADO.NET sends a DataTable as one with almost no extra code.

1. Create a table type

CREATE TYPE dbo.OrderLineList AS TABLE
(
    ProductId int           NOT NULL,
    Quantity  int           NOT NULL CHECK (Quantity > 0),
    UnitPrice decimal(10,2) NOT NULL,
    PRIMARY KEY (ProductId)
);

2. A procedure that accepts it

CREATE PROCEDURE dbo.AddOrderLines
    @OrderId int,
    @Lines   dbo.OrderLineList READONLY
AS
BEGIN
    SET NOCOUNT ON;
    INSERT INTO dbo.OrderLines (OrderId, ProductId, Quantity, UnitPrice)
    SELECT @OrderId, ProductId, Quantity, UnitPrice
    FROM @Lines;
END

Table-valued parameters are always READONLY: the procedure can read them, join them, but not modify them.

3. Pass a DataTable from C#

var lines = new DataTable();
lines.Columns.Add("ProductId", typeof(int));
lines.Columns.Add("Quantity", typeof(int));
lines.Columns.Add("UnitPrice", typeof(decimal));
foreach (var item in cart.Items)
{
    lines.Rows.Add(item.ProductId, item.Quantity, item.UnitPrice);
}

using (var con = new SqlConnection(cs))
using (var cmd = new SqlCommand("dbo.AddOrderLines", con) { CommandType = CommandType.StoredProcedure })
{
    cmd.Parameters.Add("@OrderId", SqlDbType.Int).Value = orderId;
    SqlParameter p = cmd.Parameters.Add("@Lines", SqlDbType.Structured);
    p.TypeName = "dbo.OrderLineList";
    p.Value = lines;
    con.Open();
    cmd.ExecuteNonQuery();
}

Without a DataTable

For large volumes, streaming SqlDataRecord objects avoids building the whole table in memory:

using Microsoft.SqlServer.Server; // System.Data.dll on .NET Framework

static IEnumerable<SqlDataRecord> ToRecords(IEnumerable<CartItem> items)
{
    var meta = new[]
    {
        new SqlMetaData("ProductId", SqlDbType.Int),
        new SqlMetaData("Quantity", SqlDbType.Int),
        new SqlMetaData("UnitPrice", SqlDbType.Decimal, 10, 2)
    };
    foreach (var i in items)
    {
        var r = new SqlDataRecord(meta);
        r.SetInt32(0, i.ProductId);
        r.SetInt32(1, i.Quantity);
        r.SetDecimal(2, i.UnitPrice);
        yield return r;
    }
}
// p.Value = ToRecords(cart.Items);  (the sequence must contain at least one record; pass null for an empty set)

Typical uses

Importing CSV or Excel files with SqlBulkCopy

For thousands of rows from a file, bulk copy is the tool.

Importing a spreadsheet of products or contacts is a classic admin feature. Inserting row by row works for a few dozen rows; for thousands, SqlBulkCopy streams them to SQL Server in one operation. The work around it is parsing the file correctly and rejecting bad rows before they reach the database.

1. Parse the CSV

Splitting lines on commas fails as soon as a field contains a quoted comma. .NET Framework ships a real CSV parser in the Visual Basic assembly, usable from C# (add a reference to Microsoft.VisualBasic):

using Microsoft.VisualBasic.FileIO;

public static DataTable ParseProducts(Stream csv, List<string> errors)
{
    var table = new DataTable();
    table.Columns.Add("Sku", typeof(string));
    table.Columns.Add("Name", typeof(string));
    table.Columns.Add("Price", typeof(decimal));

    using (var parser = new TextFieldParser(csv, Encoding.UTF8))
    {
        parser.TextFieldType = FieldType.Delimited;
        parser.SetDelimiters(",");
        parser.HasFieldsEnclosedInQuotes = true;
        parser.ReadFields();                         // skip header

        while (!parser.EndOfData)
        {
            long line = parser.LineNumber;
            string[] f;
            try { f = parser.ReadFields(); }
            catch (MalformedLineException ex) { errors.Add($"Line {ex.LineNumber}: malformed"); continue; }

            if (f.Length != 3 || f[0].Trim() == "" ||
                !decimal.TryParse(f[2], NumberStyles.Number, CultureInfo.InvariantCulture, out decimal price))
            {
                errors.Add($"Line {line}: invalid values");
                continue;
            }
            table.Rows.Add(f[0].Trim(), f[1].Trim(), price);
        }
    }
    return table;
}

2. Bulk copy into a staging table

CREATE TABLE dbo.ProductImport (Sku nvarchar(40) NOT NULL, Name nvarchar(200) NOT NULL, Price decimal(10,2) NOT NULL);
using (var con = new SqlConnection(cs))
{
    con.Open();
    using (var tx = con.BeginTransaction())
    {
        new SqlCommand("DELETE FROM dbo.ProductImport", con, tx).ExecuteNonQuery();

        using (var bulk = new SqlBulkCopy(con, SqlBulkCopyOptions.CheckConstraints, tx))
        {
            bulk.DestinationTableName = "dbo.ProductImport";
            bulk.ColumnMappings.Add("Sku", "Sku");      // map by name, not by position
            bulk.ColumnMappings.Add("Name", "Name");
            bulk.ColumnMappings.Add("Price", "Price");
            bulk.BatchSize = 5000;
            bulk.WriteToServer(table);
        }

        // 3. merge from staging into the real table in one set-based statement
        new SqlCommand(@"
            MERGE dbo.Products AS t
            USING dbo.ProductImport AS s ON t.Sku = s.Sku
            WHEN MATCHED THEN UPDATE SET t.Name = s.Name, t.Price = s.Price
            WHEN NOT MATCHED THEN INSERT (Sku, Name, Price) VALUES (s.Sku, s.Name, s.Price);", con, tx)
            .ExecuteNonQuery();

        tx.Commit();
    }
}

The staging table keeps the real table untouched until every row has arrived; the final statement inserts or updates in one pass. If two users may import at once, add a batch id column to the staging table instead of deleting everything. Without explicit column mappings, SqlBulkCopy maps by ordinal position, a frequent source of silently swapped columns.

The page

protected void btnImport_Click(object sender, EventArgs e)
{
    if (!fuCsv.HasFile || !fuCsv.FileName.EndsWith(".csv", StringComparison.OrdinalIgnoreCase)) return;
    var errors = new List<string>();
    DataTable rows = ParseProducts(fuCsv.PostedFile.InputStream, errors);
    if (errors.Count > 0) { blErrors.DataSource = errors.Take(50); blErrors.DataBind(); return; }
    ImportProducts(rows);
    lblResult.Text = rows.Rows.Count + " rows imported.";
}

Rejecting the whole file when any row is invalid is often clearer for users than partial imports. Upload limits and safe handling of the file are covered in Upload and download files.

BULK INSERT in T-SQL

BULK INSERT dbo.ProductImport
FROM 'D:\Imports\products.csv'
WITH (FORMAT = 'CSV', FIRSTROW = 2, CODEPAGE = '65001');

Fast and simple, but the path is read by the SQL Server service on its own machine, and the login needs the ADMINISTER BULK OPERATIONS permission. FORMAT = 'CSV' (quoted fields) requires SQL Server 2017 or later. From a web application, SqlBulkCopy is usually easier.

Excel files

For .xlsx uploads, read the sheet with a library such as ClosedXML or ExcelDataReader into a DataTable, then use the same bulk copy. Avoid the ACE OLE DB driver on servers: it requires an Office component installation and is not supported for server-side use. Passing smaller sets of rows to a stored procedure is shown in Table-valued parameters.

Checklist

Sources