Relational databases

suggest change

Dart has no database API in its standard library (there is nothing like JDBC or Go's database/sql). Instead, each database has its own package on pub.dev. The APIs are similar, though: you open a connection, run SQL with bound parameters, read rows, and use transactions.

Database Package Notes
SQLite sqlite3 Synchronous FFI bindings, in-process, great for CLI tools, tests and Flutter apps
PostgreSQL postgres Pure Dart, async, supports pools and transactions
MySQL / MariaDB mysql_client Pure Dart, async
Any of the above drift Type-safe query builder / ORM on top of SQLite or PostgreSQL

The examples below create the same users table in each database, so you can compare the APIs. All of them run on the Dart VM (server and command-line apps). In Flutter, use SQLite on the device and talk to a server database through an HTTP API, never directly.

SQLite with package:sqlite3

Add the dependency:

dependencies:
  sqlite3: ^3.7.0

package:sqlite3 calls the SQLite C library through dart:ffi. Since version 3, a build hook downloads a pre-compiled SQLite library for your platform and bundles it with your app (in Flutter too), so you don't need to install SQLite or add sqlite3_flutter_libs.

The API is synchronous: queries return results directly, not Futures. That's fine because SQLite runs in your process and queries are usually fast.

import 'package:sqlite3/sqlite3.dart';

void main() {
  // Use sqlite3.open('app.db') for a file-based database.
  final db = sqlite3.openInMemory();

  db.execute('''
    CREATE TABLE users (
      id    INTEGER PRIMARY KEY AUTOINCREMENT,
      name  TEXT NOT NULL,
      email TEXT NOT NULL UNIQUE,
      age   INTEGER
    )
  ''');

  // ? placeholders are bound to values from the list.
  db.execute(
    'INSERT INTO users (name, email, age) VALUES (?, ?, ?)',
    ['Alice', 'alice@example.com', 31],
  );
  print('inserted id: ${db.lastInsertRowId}');

  db.execute(
    'INSERT INTO users (name, email, age) VALUES (?, ?, ?)',
    ['Bob', 'bob@example.com', null],
  );

  final ResultSet rows = db.select('SELECT id, name, age FROM users ORDER BY id');
  print('columns: ${rows.columnNames}');
  for (final Row row in rows) {
    // Access columns by name or by index.
    print('${row['id']}: ${row['name']} (age ${row.columnAt(2)})');
  }

  db.execute('UPDATE users SET age = age + 1 WHERE age IS NOT NULL');
  print('updated rows: ${db.updatedRows}');

  db.close();
}

Output:

inserted id: 1
columns: [id, name, age]
1: Alice (age 31)
2: Bob (age null)
updated rows: 1

SQLite types map to Dart types like this: INTEGER -> int, REAL -> double, TEXT -> String, BLOB -> Uint8List, NULL -> null. There are no native date or boolean types; store dates as ISO-8601 text or Unix timestamps and booleans as 0/1.

Prepared statements

When you run the same statement many times, prepare it once and execute it with different parameters. Wrapping a bulk insert in a transaction makes it dramatically faster, because SQLite then syncs to disk once instead of once per row.

import 'package:sqlite3/sqlite3.dart';

void main() {
  final db = sqlite3.openInMemory();
  db.execute('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT UNIQUE, age INTEGER)');

  final people = [
    ('Carol', 'carol@example.com', 45),
    ('Dave', 'dave@example.com', 28),
    ('Erin', 'erin@example.com', 37),
  ];

  final stmt = db.prepare('INSERT INTO users (name, email, age) VALUES (?, ?, ?)');
  db.execute('BEGIN');
  try {
    for (final (name, email, age) in people) {
      stmt.execute([name, email, age]);
    }
    db.execute('COMMIT');
  } catch (_) {
    db.execute('ROLLBACK');
    rethrow;
  } finally {
    stmt.close();
  }

  final older = db.select('SELECT name FROM users WHERE age > ? ORDER BY name', [30]);
  print(older.map((r) => r['name']).toList());

  final count = db.select('SELECT count(*) AS n FROM users').first['n'];
  print('total: $count');

  db.close();
}

Output:

[Carol, Erin]
total: 3

Handling errors

Constraint violations and SQL syntax errors throw SqliteException:

import 'package:sqlite3/sqlite3.dart';

void main() {
  final db = sqlite3.openInMemory();
  db.execute('CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT UNIQUE)');
  db.execute('INSERT INTO users (email) VALUES (?)', ['alice@example.com']);

  try {
    db.execute('INSERT INTO users (email) VALUES (?)', ['alice@example.com']);
  } on SqliteException catch (e) {
    print('error ${e.extendedResultCode}: ${e.message}');
  }
  db.close();
}

Output:

error 2067: UNIQUE constraint failed: users.email

2067 is SQLITE_CONSTRAINT_UNIQUE. Checking the code is more robust than matching the message text.

PostgreSQL with package:postgres

dependencies:
  postgres: ^3.5.0

Version 3 of the package is fully async. Open a connection with an Endpoint and run queries with execute. Use Sql.named to write @name placeholders, or plain $1, $2 placeholders with a list of parameters.

import 'package:postgres/postgres.dart';

Future<void> main() async {
  final conn = await Connection.open(
    Endpoint(
      host: 'localhost',
      database: 'app',
      username: 'postgres',
      password: 'secret',
    ),
    // Local development server without TLS. Use SslMode.require in production.
    settings: ConnectionSettings(sslMode: SslMode.disable),
  );

  try {
    await conn.execute('''
      CREATE TABLE IF NOT EXISTS users (
        id    SERIAL PRIMARY KEY,
        name  TEXT NOT NULL,
        email TEXT NOT NULL UNIQUE,
        age   INTEGER
      )
    ''');

    // RETURNING gives back the generated id.
    final inserted = await conn.execute(
      Sql.named('INSERT INTO users (name, email, age) VALUES (@name, @email, @age) RETURNING id'),
      parameters: {'name': 'Alice', 'email': 'alice@example.com', 'age': 31},
    );
    print('inserted id: ${inserted.first[0]}');

    // Positional parameters: $1, $2, ...
    final result = await conn.execute(
      r'SELECT id, name, age FROM users WHERE age > $1 ORDER BY id',
      parameters: [18],
    );
    for (final row in result) {
      final m = row.toColumnMap();
      print('${m['id']}: ${m['name']} (${m['age']})');
    }

    final updated = await conn.execute(
      Sql.named('UPDATE users SET age = age + 1 WHERE email = @email'),
      parameters: {'email': 'alice@example.com'},
    );
    print('updated rows: ${updated.affectedRows}');
  } finally {
    await conn.close();
  }
}

Output (on an empty database):

inserted id: 1
1: Alice (31)
updated rows: 1

Note the r'...' raw string: without it, Dart would treat $1 as string interpolation. PostgreSQL types are decoded to natural Dart types: int, double, String, bool, DateTime for timestamp/timestamptz, Map/List for json/jsonb, and null for NULL.

Transactions

runTx starts a transaction, commits it when the callback completes and rolls it back if the callback throws:

import 'package:postgres/postgres.dart';

Future<void> transfer(Connection conn, int from, int to, int amount) async {
  await conn.runTx((tx) async {
    final res = await tx.execute(
      Sql.named('UPDATE accounts SET balance = balance - @amt WHERE id = @id AND balance >= @amt'),
      parameters: {'amt': amount, 'id': from},
    );
    if (res.affectedRows != 1) {
      throw StateError('insufficient funds'); // causes ROLLBACK
    }
    await tx.execute(
      Sql.named('UPDATE accounts SET balance = balance + @amt WHERE id = @id'),
      parameters: {'amt': amount, 'id': to},
    );
  });
}

Use the tx session inside the callback, not the outer conn; queries on conn would run outside the transaction.

Connection pools

A server handles many requests at once, and a single connection runs one query at a time. A Pool keeps several connections open and hands them out as needed. It has the same execute and runTx methods as Connection:

import 'package:postgres/postgres.dart';

final pool = Pool.withEndpoints(
  [
    Endpoint(host: 'localhost', database: 'app', username: 'postgres', password: 'secret'),
  ],
  settings: PoolSettings(
    maxConnectionCount: 10,
    sslMode: SslMode.disable,
  ),
);

Future<int> countUsers() async {
  final result = await pool.execute('SELECT count(*) FROM users');
  return result.first[0] as int;
}

Create the pool once at startup and close it with await pool.close() on shutdown.

Handling errors

Errors reported by the server throw ServerException, which carries the SQLSTATE code:

try {
  await conn.execute(
    Sql.named('INSERT INTO users (name, email) VALUES (@n, @e)'),
    parameters: {'n': 'Alice', 'e': 'alice@example.com'},
  );
} on ServerException catch (e) {
  if (e.code == '23505') {
    print('email already registered');
  } else {
    rethrow;
  }
}

23505 is unique_violation; 23503 is foreign_key_violation, 23502 is not_null_violation.

MySQL and MariaDB with package:mysql_client

dependencies:
  mysql_client: ^0.0.27

Named parameters use the :name syntax:

import 'package:mysql_client/mysql_client.dart';

Future<void> main() async {
  final conn = await MySQLConnection.createConnection(
    host: 'localhost',
    port: 3306,
    userName: 'root',
    password: 'secret',
    databaseName: 'app',
    secure: false, // set to true to use TLS
  );
  await conn.connect();

  try {
    await conn.execute('''
      CREATE TABLE IF NOT EXISTS users (
        id    INT AUTO_INCREMENT PRIMARY KEY,
        name  VARCHAR(100) NOT NULL,
        email VARCHAR(255) NOT NULL UNIQUE,
        age   INT
      )
    ''');

    final res = await conn.execute(
      'INSERT INTO users (name, email, age) VALUES (:name, :email, :age)',
      {'name': 'Alice', 'email': 'alice@example.com', 'age': 31},
    );
    print('inserted id: ${res.lastInsertID}');

    final rows = await conn.execute('SELECT id, name, age FROM users WHERE age > :min', {'min': 18});
    for (final row in rows.rows) {
      // Values come back as strings (or null); convert as needed.
      final id = int.parse(row.colByName('id')!);
      print('$id: ${row.colByName('name')} (${row.colByName('age')})');
    }

    await conn.transactional((tx) async {
      await tx.execute('UPDATE users SET age = age + 1 WHERE id = :id', {'id': 1});
    });
  } finally {
    await conn.close();
  }
}

Output (on an empty database):

inserted id: 1
1: Alice (31)

colByName returns String?; use row.typedColByName<int>('id') or row.assoc() (a Map<String, String?>) if you prefer. For servers, MySQLConnectionPool provides pooling with the same execute method.

Mapping rows to classes

Passing Maps around gets error-prone quickly. A small model class with a constructor that reads a row keeps column names and casts in one place:

import 'package:sqlite3/sqlite3.dart';

class User {
  final int id;
  final String name;
  final int? age;

  User({required this.id, required this.name, this.age});

  factory User.fromRow(Row row) => User(
        id: row['id'] as int,
        name: row['name'] as String,
        age: row['age'] as int?,
      );

  @override
  String toString() => 'User($id, $name, ${age ?? "?"})';
}

class UserRepository {
  final Database db;
  UserRepository(this.db);

  int create(String name, int? age) {
    db.execute('INSERT INTO users (name, age) VALUES (?, ?)', [name, age]);
    return db.lastInsertRowId;
  }

  User? findById(int id) {
    final rows = db.select('SELECT id, name, age FROM users WHERE id = ?', [id]);
    return rows.isEmpty ? null : User.fromRow(rows.first);
  }

  List<User> all() =>
      db.select('SELECT id, name, age FROM users ORDER BY name').map(User.fromRow).toList();
}

void main() {
  final db = sqlite3.openInMemory();
  db.execute('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT NOT NULL, age INTEGER)');

  final repo = UserRepository(db);
  final id = repo.create('Zoe', 22);
  repo.create('Adam', null);

  print(repo.findById(id));
  print(repo.findById(99));
  print(repo.all());
  db.close();
}

Output:

User(1, Zoe, 22)
null
[User(2, Adam, ?), User(1, Zoe, 22)]

Keeping SQL inside a repository class also makes it easy to swap the database in tests: an in-memory SQLite database is fast and needs no server.

Type-safe queries with drift

For larger apps, writing SQL strings and casting columns by hand gets tedious. drift generates Dart code from table definitions (or from .drift files containing SQL) and checks queries at build time. It supports SQLite everywhere, including Flutter and the web, and PostgreSQL through drift_postgres.

import 'package:drift/drift.dart';

part 'database.g.dart';

class Users extends Table {
  IntColumn get id => integer().autoIncrement()();
  TextColumn get name => text().withLength(min: 1, max: 100)();
  IntColumn get age => integer().nullable()();
}

@DriftDatabase(tables: [Users])
class AppDatabase extends _$AppDatabase {
  AppDatabase(super.e);

  @override
  int get schemaVersion => 1;

  Future<List<User>> adults() =>
      (select(users)..where((u) => u.age.isBiggerOrEqualValue(18))).get();
}

Running dart run build_runner build generates the User data class, the _$AppDatabase base class and the query code. Drift also handles schema migrations and can turn queries into Streams that re-emit when the underlying tables change, which is handy in Flutter UIs.

Best practices

Feedback about page:

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



Table Of Contents