MySQL

suggest change

MySQL (and its fork MariaDB) is one of the most widely used relational databases. From C# you talk to it through an ADO.NET provider, the same Connection / Command / DataReader model used for SQL Server or SQLite.

There are two main providers:

The APIs look almost the same (MySqlConnection, MySqlCommand, MySqlDataReader), so most of the code below works with either one after you change the using. This article uses MySqlConnector.

Installing

dotnet add package MySqlConnector

To get a server for local testing, run one in Docker:

docker run -d --name mysql -p 3306:3306 \
  -e MYSQL_ROOT_PASSWORD=secret -e MYSQL_DATABASE=shop mysql:8.4

Connection strings

// Hard-coded for the example; in real apps load it from configuration / secrets
const string ConnStr =
    "Server=localhost;Port=3306;Database=shop;User ID=root;Password=secret;" +
    "SslMode=Preferred;Pooling=true;Maximum Pool Size=50;";

MySqlConnectionStringBuilder builds the string without typos and escapes values for you:

using MySqlConnector;

var csb = new MySqlConnectionStringBuilder
{
    Server = "localhost",
    Database = "shop",
    UserID = "root",
    Password = "secret",
    SslMode = MySqlSslMode.Required,
};
string connStr = csb.ConnectionString;

Connection pooling is on by default. Calling Dispose on a connection returns it to the pool instead of closing the socket, so open connections late and dispose them early.

Connecting and running a query

using MySqlConnector;

await using var conn = new MySqlConnection(ConnStr);
await conn.OpenAsync();

Console.WriteLine($"Server version: {conn.ServerVersion}");

await using var cmd = new MySqlCommand(
    "SELECT id, name, price FROM products ORDER BY id", conn);
await using var reader = await cmd.ExecuteReaderAsync();

while (await reader.ReadAsync())
{
    int id = reader.GetInt32(0);
    string name = reader.GetString(1);
    decimal price = reader.GetDecimal(2);
    Console.WriteLine($"{id}: {name} {price:C}");
}

Use ExecuteNonQueryAsync for statements that don't return rows. It returns the number of affected rows:

await using var create = new MySqlCommand("""
    CREATE TABLE IF NOT EXISTS products (
        id         INT AUTO_INCREMENT PRIMARY KEY,
        name       VARCHAR(100) NOT NULL UNIQUE,
        price      DECIMAL(10,2) NOT NULL,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
    )
    """, conn);
await create.ExecuteNonQueryAsync();

ExecuteScalarAsync returns the first column of the first row:

await using var count = new MySqlCommand("SELECT COUNT(*) FROM products", conn);
long n = Convert.ToInt64(await count.ExecuteScalarAsync()); // COUNT(*) is BIGINT

Parameters (never concatenate SQL)

Always pass values as parameters. That protects you from SQL injection and from problems with quoting, dates, and decimals:

await using var insert = new MySqlCommand(
    "INSERT INTO products (name, price) VALUES (@name, @price)", conn);
insert.Parameters.AddWithValue("@name", "Keyboard");
insert.Parameters.AddWithValue("@price", 49.99m);
await insert.ExecuteNonQueryAsync();

// MySQL-specific: id generated by AUTO_INCREMENT
long newId = insert.LastInsertedId;

If you need to control the database type, add a typed parameter:

insert.Parameters.Add(new MySqlParameter("@name", MySqlDbType.VarChar, 100) { Value = "Mouse" });

To store NULL, use DBNull.Value, not null. To read a nullable column, check IsDBNull first:

string? description = reader.IsDBNull(3) ? null : reader.GetString(3);

Mapping rows to objects

public record Product(int Id, string Name, decimal Price, DateTime CreatedAt);

static async Task<List<Product>> GetProductsAsync(
    MySqlConnection conn, decimal maxPrice, CancellationToken ct = default)
{
    await using var cmd = new MySqlCommand(
        "SELECT id, name, price, created_at FROM products WHERE price <= @max", conn);
    cmd.Parameters.AddWithValue("@max", maxPrice);

    var result = new List<Product>();
    await using var reader = await cmd.ExecuteReaderAsync(ct);

    int idOrd = reader.GetOrdinal("id");
    int nameOrd = reader.GetOrdinal("name");
    int priceOrd = reader.GetOrdinal("price");
    int createdOrd = reader.GetOrdinal("created_at");

    while (await reader.ReadAsync(ct))
    {
        result.Add(new Product(
            reader.GetInt32(idOrd),
            reader.GetString(nameOrd),
            reader.GetDecimal(priceOrd),
            reader.GetDateTime(createdOrd)));
    }
    return result;
}

Transactions

Group statements in a transaction so that either all of them succeed or none do. MySqlConnector requires you to set MySqlCommand.Transaction explicitly. If you forget, it throws an InvalidOperationException.

await using var conn = new MySqlConnection(ConnStr);
await conn.OpenAsync();
await using var tx = await conn.BeginTransactionAsync();

try
{
    await using var debit = new MySqlCommand(
        "UPDATE accounts SET balance = balance - @amt WHERE id = @id", conn, tx);
    debit.Parameters.AddWithValue("@amt", 100m);
    debit.Parameters.AddWithValue("@id", 1);
    await debit.ExecuteNonQueryAsync();

    await using var credit = new MySqlCommand(
        "UPDATE accounts SET balance = balance + @amt WHERE id = @id", conn, tx);
    credit.Parameters.AddWithValue("@amt", 100m);
    credit.Parameters.AddWithValue("@id", 2);
    await credit.ExecuteNonQueryAsync();

    await tx.CommitAsync();
}
catch
{
    await tx.RollbackAsync();
    throw;
}

Transactions only work with the InnoDB storage engine, which has been the default since MySQL 5.5.

Handling errors

Server errors throw a MySqlException. Its ErrorCode property is a MySqlErrorCode enum, so you can handle specific errors without matching numbers yourself:

try
{
    await insert.ExecuteNonQueryAsync();
}
catch (MySqlException ex) when (ex.ErrorCode == MySqlErrorCode.DuplicateKeyEntry)
{
    Console.WriteLine("A product with that name already exists.");
}

MySqlDataSource and dependency injection

In MySqlConnector 2.2 and later, MySqlDataSource is the recommended way to manage connections. Create it once, share it across the app, and ask it for connections:

await using var dataSource = new MySqlDataSource(ConnStr);

await using var conn = await dataSource.OpenConnectionAsync();
// use conn as before

In ASP.NET Core, add the MySqlConnector.DependencyInjection package and register the data source:

builder.Services.AddMySqlDataSource(builder.Configuration.GetConnectionString("Default")!);

app.MapGet("/products/count", async (MySqlDataSource db) =>
{
    await using var conn = await db.OpenConnectionAsync();
    await using var cmd = new MySqlCommand("SELECT COUNT(*) FROM products", conn);
    return Convert.ToInt64(await cmd.ExecuteScalarAsync());
});

Dapper

Dapper is a micro-ORM that removes most of the reader boilerplate and works with any DbConnection:

dotnet add package Dapper
using Dapper;
using MySqlConnector;

await using var conn = new MySqlConnection(ConnStr);

// Dapper opens and closes the connection if it isn't already open.
// Columns map to properties by name, so alias snake_case columns.
var cheap = await conn.QueryAsync<Product>(
    "SELECT id AS Id, name AS Name, price AS Price, created_at AS CreatedAt " +
    "FROM products WHERE price < @MaxPrice",
    new { MaxPrice = 20m });

long id = await conn.ExecuteScalarAsync<long>(
    "INSERT INTO products (name, price) VALUES (@Name, @Price); SELECT LAST_INSERT_ID();",
    new { Name = "Cable", Price = 5.50m });

Entity Framework Core

For a full ORM, use the community Pomelo.EntityFrameworkCore.MySql provider, which is built on MySqlConnector. Pick the package version whose major version matches your EF Core version:

dotnet add package Pomelo.EntityFrameworkCore.MySql
using Microsoft.EntityFrameworkCore;

public class ShopContext(DbContextOptions<ShopContext> options) : DbContext(options)
{
    public DbSet<ProductEntity> Products => Set<ProductEntity>();
}

public class ProductEntity
{
    public int Id { get; set; }
    public string Name { get; set; } = "";
    public decimal Price { get; set; }
}

// Program.cs
var connStr = builder.Configuration.GetConnectionString("Default")!;
builder.Services.AddDbContext<ShopContext>(options =>
    options.UseMySql(connStr, ServerVersion.AutoDetect(connStr)));

ServerVersion.AutoDetect connects to the server at startup to find out which SQL features it supports. To avoid that round trip, pass an explicit version, e.g. new MySqlServerVersion(new Version(8, 4, 0)). Oracle also ships an EF Core provider, MySql.EntityFrameworkCore, which is configured with UseMySQL(...).

Tips

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents