用 Dart 编写的用于 Dart 的原生 MySQL 客户端

有关示例和用法的更多信息,请参阅 示例 目录

路线图

  • 使用 mysql_native_password 进行身份验证
  • 基本连接
  • 连接池
  • 查询占位符
  • 事务
  • 预准备语句(真实,非模拟)
  • SSL 连接
  • 使用 caching_sha2_password 进行身份验证(MySQL 8 默认)
  • 使用预准备语句时以二进制形式发送数据(不全部转换为字符串)
  • 多个结果集

用法

创建连接池

final pool = MySQLConnectionPool(
    host: '127.0.0.1',
    port: 3306,
    userName: 'your_user',
    password: 'your_password',
    maxConnections: 10,
    databaseName: 'your_database_name', // optional,
  );

查询数据库

var result = await pool.execute("SELECT * FROM book WHERE id = :id", {"id": 1});

打印结果

  for (final row in result.rows) {
    print(row.assoc());
  }

预准备语句

此库支持真实的预准备语句(使用二进制协议)。

预准备语句

var stmt = await conn.prepare(
  "INSERT INTO book (author_id, title, price, created_at) VALUES (?, ?, ?, ?)",
);

使用参数执行

await stmt.execute([null, 'Some book 1', 120, '2022-01-01']);
await stmt.execute([null, 'Some book 2', 10, '2022-01-01']);

取消预准备语句

await stmt.deallocate();

事务

要执行事务中的查询,您可以使用 `connection` 或 `pool` 对象上的 `transactional()` 方法
示例

await pool.transactional((conn) async {
  await conn.execute("UPDATE book SET price = :price", {"price": 300});
  await conn.execute("UPDATE book_author SET name = :name", {"name": "John Doe"});
});

发生异常时,事务将自动回滚。

测试

要运行测试,请执行

dart test

GitHub

查看 Github