Select, Insert, Update and Delete Data in an Access File with C#

To read and write a Microsoft Access database (.accdb or .mdb) from C#, open an OleDbConnection with the Access Database Engine provider and run ordinary SQL commands against it. The examples below cover all four CRUD operations against a single table.

OleDb is Windows-only. On .NET 8 and later, add the System.Data.OleDb NuGet package (it is built into .NET Framework) and target Windows in the project file:

<TargetFramework>net8.0-windows</TargetFramework>

The provider and the 32/64-bit trap

The old Microsoft.Jet.OLEDB.4.0 provider only reads .mdb files and only exists as a 32-bit component, so it fails in any 64-bit process. Use the ACE provider instead, which handles both file formats. It ships with Office, or separately as the Microsoft Access Database Engine 2016 Redistributable.

The engine’s bitness must match your process. If you install the 64-bit engine, run your app as x64. If only the 32-bit engine is present (common on machines with 32-bit Office), set <PlatformTarget>x86</PlatformTarget>. A mismatch shows up as “The ‘Microsoft.ACE.OLEDB.12.0’ provider is not registered on the local machine”, which is misleading: the provider is installed, just not for your bitness.

The sample table

The examples use a table named TABLE1:

ID (AutoNumber)NAME (Short Text)SURNAME (Short Text)
1JackSparrow

Full example

using System.Data;
using System.Data.OleDb;

const string connectionString =
    @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\data\csharpexamples.accdb";

using var connection = new OleDbConnection(connectionString);
connection.Open();

int newId = Insert(connection, "Brad", "Pitt");
Update(connection, newId, "Bradley", "Pitt");
PrintAll(connection);
Delete(connection, newId);

static void PrintAll(OleDbConnection connection)
{
    using var command = new OleDbCommand(
        "SELECT TOP 10 [ID], [NAME], [SURNAME] FROM TABLE1 ORDER BY [ID]", connection);
    using var reader = command.ExecuteReader();

    while (reader.Read())
    {
        int id = reader.GetInt32(0);
        string name = reader.GetString(1);
        string surname = reader.IsDBNull(2) ? "" : reader.GetString(2);
        Console.WriteLine($"{id}: {name} {surname}");
    }
}

static int Insert(OleDbConnection connection, string name, string? surname)
{
    using var command = new OleDbCommand(
        "INSERT INTO TABLE1 ([NAME], [SURNAME]) VALUES (?, ?)", connection);
    command.Parameters.Add("NAME", OleDbType.VarWChar, 255).Value = name;
    command.Parameters.Add("SURNAME", OleDbType.VarWChar, 255).Value =
        (object?)surname ?? DBNull.Value;
    command.ExecuteNonQuery();

    // Must run on the same open connection as the INSERT.
    using var identity = new OleDbCommand("SELECT @@IDENTITY", connection);
    return Convert.ToInt32(identity.ExecuteScalar());
}

static int Update(OleDbConnection connection, int id, string name, string? surname)
{
    using var command = new OleDbCommand(
        "UPDATE TABLE1 SET [NAME] = ?, [SURNAME] = ? WHERE [ID] = ?", connection);
    command.Parameters.Add("NAME", OleDbType.VarWChar, 255).Value = name;
    command.Parameters.Add("SURNAME", OleDbType.VarWChar, 255).Value =
        (object?)surname ?? DBNull.Value;
    command.Parameters.Add("ID", OleDbType.Integer).Value = id;
    return command.ExecuteNonQuery();
}

static int Delete(OleDbConnection connection, int id)
{
    using var command = new OleDbCommand("DELETE FROM TABLE1 WHERE [ID] = ?", connection);
    command.Parameters.Add("ID", OleDbType.Integer).Value = id;
    return command.ExecuteNonQuery();
}

Update and Delete return the number of affected rows, so a result of 0 tells you the ID did not exist.

Parameters are positional

OleDb ignores parameter names. Each ? in the SQL is matched to the parameter at the same position in the collection, so the order you add them is what counts. Add them in a different order and Access will happily write the surname into the name column. The names in the code above are only there for readability.

Never build the SQL by concatenating user input. Besides SQL injection, a name such as O'Brien breaks the statement.

Setting the OleDbType explicitly matters most for dates. AddWithValue maps a DateTime to OleDbType.DBTimeStamp, which carries fractions of a second that Access cannot store, and the result is a “Data type mismatch in criteria expression” error. Use OleDbType.Date for Access Date/Time columns.

Reserved words and brackets

NAME is a reserved word in Access SQL, which is why the column names are wrapped in square brackets. Brackets are harmless on every identifier, so using them everywhere saves you from guessing which words are reserved.

Async and concurrency

OleDbCommand inherits ExecuteNonQueryAsync and ExecuteReaderAsync from DbCommand, but OleDb has no real asynchronous I/O: those methods run synchronously and return a completed task. In a desktop app, wrap the database work in Task.Run if it takes long enough to freeze the UI.

Access is a file-based database meant for a handful of users. It locks the file through a .laccdb (or .ldb) file next to it, so the process needs write permission on the folder, not just the file. It is also not supported for use from server-side code such as an ASP.NET site. If the data has outgrown a single desktop app, move it to SQL Server, SQLite or MySQL.

Related examples

2 thoughts on “Select, Insert, Update and Delete Data in an Access File with C#”

Leave a Comment