MySQL

suggest change

The Relational databases article shows a short MySQL example next to SQLite and PostgreSQL. This article goes further into MySQL (and MariaDB) with package:mysql_client: connection options and TLS, how parameters really work, typed column access, prepared statements, transactions, upserts, streaming large results, connection pools and error codes.

mysql_client is a pure Dart, async driver that speaks the MySQL wire protocol. It runs on the Dart VM (servers, CLI tools). A Flutter app should not connect to MySQL directly; put an HTTP API in between (see REST APIs).

Setup

dependencies:
  mysql_client: ^0.0.27

For a local server, Docker is the quickest option:

docker run -d --name mysql -p 3306:3306 \
  -e MYSQL_ROOT_PASSWORD=rootpw \
  -e MYSQL_DATABASE=app \
  -e MYSQL_USER=app -e MYSQL_PASSWORD=secret \
  mysql:8.4

This creates database app and a user app with full rights on it. Use that user from your program, not root.

Connecting

MySQLConnection.createConnection opens the socket; connect() performs the handshake and authentication:

import 'dart:io';
import 'package:mysql_client/mysql_client.dart';

Future<MySQLConnection> openConnection() async {
  final env = Platform.environment;
  final conn = await MySQLConnection.createConnection(
    host: env['MYSQL_HOST'] ?? '127.0.0.1',
    port: int.parse(env['MYSQL_PORT'] ?? '3306'),
    userName: env['MYSQL_USER'] ?? 'app',
    password: env['MYSQL_PASSWORD'] ?? 'secret',
    databaseName: env['MYSQL_DATABASE'] ?? 'app',
    // secure: true is the default
  );
  await conn.connect(timeoutMs: 5000);
  return conn;
}

Future<void> main() async {
  final conn = await openConnection();
  try {
    final res = await conn.execute('SELECT VERSION() AS v, DATABASE() AS db');
    final row = res.rows.first;
    print('server ${row.colByName('v')}, database ${row.colByName('db')}');
    print('connected: ${conn.connected}');
  } finally {
    await conn.close();
  }
}

Output:

server 8.4.6, database app
connected: true

Things worth knowing about the connection options:

Executing SQL and reading results

execute() returns an IResultSet. For INSERT/UPDATE/DELETE it carries affectedRows and lastInsertID (both BigInt); for SELECT it carries rows, cols and numOfRows.

Future<void> demo(MySQLConnection conn) async {
  await conn.execute('DROP TABLE IF EXISTS products');
  await conn.execute('''
    CREATE TABLE products (
      id         INT AUTO_INCREMENT PRIMARY KEY,
      sku        VARCHAR(32)   NOT NULL UNIQUE,
      name       VARCHAR(200)  NOT NULL,
      price      DECIMAL(10,2) NOT NULL,
      stock      INT           NOT NULL DEFAULT 0,
      active     BOOLEAN       NOT NULL DEFAULT TRUE,
      created_at DATETIME      NOT NULL DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
  ''');

  final ins = await conn.execute(
    'INSERT INTO products (sku, name, price, stock) VALUES (:sku, :name, :price, :stock)',
    {'sku': 'KB-01', 'name': 'Keyboard', 'price': 49.90, 'stock': 12},
  );
  print('id=${ins.lastInsertID} affected=${ins.affectedRows}');

  await conn.execute(
    'INSERT INTO products (sku, name, price, stock) VALUES '
    "('MS-01', 'Mouse', 19.99, 40), ('MN-27', 'Monitor 27\"', 279.00, 0)",
  );

  final upd = await conn.execute(
    'UPDATE products SET active = FALSE WHERE stock = :stock',
    {'stock': 0},
  );
  print('deactivated ${upd.affectedRows}');

  final res = await conn.execute('SELECT id, sku, price, active FROM products ORDER BY id');
  print('columns: ${res.cols.map((c) => c.name).toList()}, rows: ${res.numOfRows}');
  for (final row in res.rows) {
    print(row.assoc());
  }
}

Output:

id=1 affected=1
deactivated 1
columns: [id, sku, price, active], rows: 3
{id: 1, sku: KB-01, price: 49.90, active: 1}
{id: 2, sku: MS-01, price: 19.99, active: 1}
{id: 3, sku: MN-27, price: 279.00, active: 0}

Convert lastInsertID with .toInt() when you need an int.

How :name parameters work

Named parameters passed to execute() are substituted on the client: strings are escaped and quoted, numbers are inserted as-is, bool becomes TRUE/FALSE and null becomes NULL. Any other object is converted with toString() and quoted. This is safe against SQL injection, but keep in mind:

Never build SQL by string interpolation. The driver enables multi-statement queries, so "... WHERE name = '$name'" lets an attacker append ; DROP TABLE products to your query.

Multiple statements in one call

Because multi-statements are enabled, one execute() can return several result sets. IResultSet is itself iterable over them:

final results = await conn.execute(
  'SELECT COUNT(*) AS n FROM products; SELECT MAX(price) AS top FROM products',
);
for (final rs in results) {
  print(rs.rows.first.assoc());
}

Output:

{n: 3}
{top: 279.00}

Typed column access

The text protocol returns every value as String?. The driver offers typed accessors that look at the column's MySQL type:

Method Returns
row.colAt(i), row.colByName(name) String?
row.typedColAt<T>(i), row.typedColByName<T>(name) T?, with T one of String, int, double, num, bool
row.assoc() Map<String, String?>
row.typedAssoc() Map<String, dynamic> with ints, doubles, bools converted

Conversion is checked against the column type: asking for int on a VARCHAR column throws MySQLProtocolException. A few MySQL types need extra care:

final res = await conn.execute(
  'SELECT id, name, price, stock, active, created_at FROM products WHERE sku = :sku',
  {'sku': 'KB-01'},
);
final row = res.rows.first;

final int id = row.typedColByName<int>('id')!;
final bool active = row.typedColByName<bool>('active')!;
final int priceCents = (double.parse(row.colByName('price')!) * 100).round();
final DateTime created = DateTime.parse(row.colByName('created_at')!);

print('$id ${row.colByName('name')} $priceCents cents, active=$active, '
    'created ${created.year}');
print(row.typedAssoc());

Output:

1 Keyboard 4990 cents, active=true, created 2026
{id: 1, name: Keyboard, price: 49.90, stock: 12, active: true, created_at: 2026-10-17 09:30:00}

To write a DateTime, format it in the shape MySQL expects. Storing UTC and converting on display avoids time zone confusion:

String toMySql(DateTime t) {
  final u = t.toUtc();
  String two(int n) => n.toString().padLeft(2, '0');
  return '${u.year}-${two(u.month)}-${two(u.day)} '
      '${two(u.hour)}:${two(u.minute)}:${two(u.second)}';
}

DateTime fromMySql(String s) => DateTime.parse('${s.replaceFirst(' ', 'T')}Z');

void main() {
  final s = toMySql(DateTime.utc(2026, 3, 9, 7, 5, 0));
  print(s);
  print(fromMySql(s));
}

Output:

2026-03-09 07:05:00
2026-03-09 07:05:00.000Z

Prepared statements

conn.prepare() creates a real server-side prepared statement with ? placeholders. The SQL is parsed once and can be executed many times; parameters travel separately from the SQL text. Free it with deallocate() when done (it's freed automatically when the connection closes).

final stmt = await conn.prepare(
  'INSERT INTO products (sku, name, price, stock) VALUES (?, ?, ?, ?)',
);
try {
  final items = [
    ('CB-01', 'USB-C cable', 9.5, 100),
    ('HD-01', 'Headphones', 89.0, 7),
  ];
  for (final (sku, name, price, stock) in items) {
    final r = await stmt.execute([sku, name, price, stock]);
    print('inserted $sku -> id ${r.lastInsertID}');
  }
} finally {
  await stmt.deallocate();
}

final q = await conn.prepare('SELECT name, stock FROM products WHERE stock >= ? ORDER BY stock');
final r = await q.execute([10]);
for (final row in r.rows) {
  print('${row.colAt(0)}: ${row.typedColAt<int>(1)}');
}
await q.deallocate();

Output:

inserted CB-01 -> id 4
inserted HD-01 -> id 5
Keyboard: 12
Mouse: 40
USB-C cable: 100

The number of values must match the number of ? exactly, or execute throws. Pass null for SQL NULL. In version 0.0.27 all non-null parameters are sent as strings (MySQL converts them to the column type), so the same DateTime formatting rule applies.

Mapping rows to classes

A model class with a fromRow factory keeps column names and conversions in one place. The general pattern is covered in Relational databases; here is the MySQL-flavored version with typed accessors:

class Product {
  final int id;
  final String sku;
  final String name;
  final int priceCents;
  final int stock;

  Product(this.id, this.sku, this.name, this.priceCents, this.stock);

  factory Product.fromRow(ResultSetRow r) => Product(
        r.typedColByName<int>('id')!,
        r.colByName('sku')!,
        r.colByName('name')!,
        (double.parse(r.colByName('price')!) * 100).round(),
        r.typedColByName<int>('stock')!,
      );

  @override
  String toString() => 'Product($id, $sku, $name, ${priceCents / 100}, stock $stock)';
}

class ProductRepo {
  final MySQLConnection conn;
  ProductRepo(this.conn);

  static const _cols = 'id, sku, name, price, stock';

  Future<Product?> bySku(String sku) async {
    final res = await conn.execute('SELECT $_cols FROM products WHERE sku = :sku', {'sku': sku});
    return res.rows.isEmpty ? null : Product.fromRow(res.rows.first);
  }

  Future<List<Product>> inStock({int limit = 10}) async {
    final res = await conn.execute(
      'SELECT $_cols FROM products WHERE stock > 0 ORDER BY price LIMIT :limit',
      {'limit': limit},
    );
    return res.rows.map(Product.fromRow).toList();
  }
}

_cols is a constant, so interpolating it is safe; user values still go through :sku and :limit.

Transactions

transactional() runs START TRANSACTION, calls your function, and runs COMMIT. If the function throws anything, it runs ROLLBACK and rethrows. It returns your function's result. Use SELECT ... FOR UPDATE to lock rows you're about to change:

class OutOfStock implements Exception {
  final String sku;
  OutOfStock(this.sku);
  @override
  String toString() => 'OutOfStock($sku)';
}

Future<int> placeOrder(MySQLConnection conn, String sku, int qty) {
  return conn.transactional((tx) async {
    final res = await tx.execute(
      'SELECT id, stock FROM products WHERE sku = :sku FOR UPDATE',
      {'sku': sku},
    );
    if (res.rows.isEmpty) throw ArgumentError('unknown sku $sku');
    final row = res.rows.first;
    final stock = row.typedColByName<int>('stock')!;
    if (stock < qty) throw OutOfStock(sku);

    await tx.execute(
      'UPDATE products SET stock = stock - :qty WHERE id = :id',
      {'qty': qty, 'id': row.typedColByName<int>('id')},
    );
    return stock - qty;
  });
}

Future<void> orders(MySQLConnection conn) async {
  print('left: ${await placeOrder(conn, 'KB-01', 5)}');
  try {
    await placeOrder(conn, 'KB-01', 50);
  } on OutOfStock catch (e) {
    print('rolled back: $e');
  }
  final res = await conn.execute("SELECT stock FROM products WHERE sku = 'KB-01'");
  print('stock now: ${res.rows.first.colAt(0)}');
}

Output:

left: 7
rolled back: OutOfStock(KB-01)
stock now: 7

Notes:

Upserts

MySQL's INSERT ... ON DUPLICATE KEY UPDATE inserts a row or updates it if a PRIMARY KEY or UNIQUE column collides. affectedRows tells you what happened: 1 = inserted, 2 = updated, 0 = existing row already had those values.

Future<void> upsertStock(MySQLConnection conn, String sku, String name, int stock) async {
  final res = await conn.execute('''
    INSERT INTO products (sku, name, price, stock) VALUES (:sku, :name, 0, :stock)
    ON DUPLICATE KEY UPDATE stock = VALUES(stock)
  ''', {'sku': sku, 'name': name, 'stock': stock});
  final what = switch (res.affectedRows.toInt()) {
    1 => 'inserted',
    2 => 'updated',
    _ => 'unchanged',
  };
  print('$sku: $what');
}

// await upsertStock(conn, 'MS-01', 'Mouse', 35);
// await upsertStock(conn, 'MS-01', 'Mouse', 35);
// await upsertStock(conn, 'PD-01', 'Mouse pad', 80);

Output:

MS-01: updated
MS-01: unchanged
PD-01: inserted

VALUES(col) still works in MySQL 8.4 but is deprecated; the newer form is INSERT ... VALUES (...) AS new ON DUPLICATE KEY UPDATE stock = new.stock. MariaDB only supports VALUES(col).

Streaming large result sets

By default all rows are read into memory before execute() completes. For exports or batch jobs over millions of rows, pass iterable: true (the third positional argument) and consume rowsStream; rows arrive as the server sends them:

Future<void> exportCsv(MySQLConnection conn, IOSink out) async {
  final res = await conn.execute('SELECT id, sku, stock FROM products ORDER BY id', {}, true);
  var n = 0;
  await for (final row in res.rowsStream) {
    out.writeln('${row.colAt(0)},${row.colAt(1)},${row.colAt(2)}');
    n++;
  }
  print('exported $n rows');
}

With an iterable result, rows and numOfRows throw; use only rowsStream. The connection is busy until the stream is drained, so don't issue other queries on it inside the loop. conn.prepare(sql, true) gives the same behavior for prepared statements. For CSV formatting with proper quoting, see CSV.

Connection pools

A server handling concurrent requests needs more than one connection, since a connection executes one query at a time. MySQLConnectionPool opens connections lazily up to maxConnections and has the same execute, prepare and transactional methods:

final pool = MySQLConnectionPool(
  host: '127.0.0.1',
  port: 3306,
  userName: 'app',
  password: 'secret',
  databaseName: 'app',
  maxConnections: 10,
  collation: 'utf8mb4_general_ci', // the pool's default is utf8_general_ci
);

Future<void> main() async {
  final results = await Future.wait([
    for (var i = 0; i < 5; i++)
      pool.execute('SELECT CONNECTION_ID() AS cid, :i AS i', {'i': i}),
  ]);
  for (final r in results) {
    print(r.rows.first.assoc());
  }
  print('open connections: ${pool.allConnectionsQty}');
  await pool.close();
}

Output (connection ids vary):

{cid: 21, i: 0}
{cid: 22, i: 1}
{cid: 23, i: 2}
{cid: 24, i: 3}
{cid: 25, i: 4}
open connections: 5

pool.withConnection((conn) async { ... }) lends you one connection for several statements, for example to use a prepared statement or SET session variables.

The pool in version 0.0.27 is minimal, so be aware of two limitations:

A small wrapper fixes the first problem by catching errors inside the callback and rethrowing them after the connection has been released:

Future<T> inTransaction<T>(
    MySQLConnectionPool pool, Future<T> Function(MySQLConnection) body) async {
  Object? error;
  StackTrace? stack;
  final result = await pool.withConnection<T?>((conn) async {
    try {
      return await conn.transactional(body);
    } catch (e, st) {
      error = e;
      stack = st;
      return null;
    }
  });
  if (error != null) Error.throwWithStackTrace(error!, stack!);
  return result as T;
}

Handling errors

The driver throws three exception types, all subclasses of MySQLException:

Exception Meaning Connection after error
MySQLServerException Error reported by the server; has errorCode still usable
MySQLClientException Misuse or driver error (missing parameter, closed connection) depends; check conn.connected
MySQLProtocolException Unexpected packet or failed type conversion often closed

Common server error codes:

Code Name Typical cause
1045 ER_ACCESS_DENIED_ERROR wrong user or password
1049 ER_BAD_DB_ERROR database doesn't exist
1062 ER_DUP_ENTRY duplicate value in a UNIQUE / PRIMARY KEY column
1146 ER_NO_SUCH_TABLE table doesn't exist
1213 ER_LOCK_DEADLOCK deadlock; retry the transaction
1452 ER_NO_REFERENCED_ROW_2 foreign key points to a missing row

The exception classes are not exported by mysql_client.dart; import them separately:

import 'package:mysql_client/exception.dart';

Future<bool> tryInsert(MySQLConnection conn, String sku, String name) async {
  try {
    await conn.execute(
      'INSERT INTO products (sku, name, price) VALUES (:sku, :name, 0)',
      {'sku': sku, 'name': name},
    );
    return true;
  } on MySQLServerException catch (e) {
    if (e.errorCode == 1062) {
      print('duplicate sku: ${e.message}');
      return false;
    }
    rethrow;
  } on MySQLClientException catch (e) {
    print('client error: $e (connected: ${conn.connected})');
    rethrow;
  }
}

// await tryInsert(conn, 'KB-01', 'Another keyboard');

Output:

duplicate sku: Duplicate entry 'KB-01' for key 'products.sku'

Deadlocks (1213) and lock wait timeouts (1205) are expected under concurrent writes in InnoDB; the right response is to retry the whole transaction a few times with a short delay, as described in Cancellation and timeouts.

Best practices

Feedback about page:

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



Table Of Contents