You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Dart连接MySQL后程序执行完成却无法自动终止

解决Dart使用MySQL连接池后程序无法自动终止的问题

你在使用mysql_client库(此前使用mysql1库时也出现相同问题)访问MySQL数据库时,代码已完整执行完毕,但程序无法自动终止,必须手动点击停止按钮才能结束。

原代码

import 'package:mysql_client/mysql_client.dart';

Future<void> main() async {
  final pool = MySQLConnectionPool(
      host: '127.0.0.1',
      port: 13306,
      userName: 'root',
      password: 'password',
      databaseName: 'dart_mysql',
      maxConnections: 10);

  var result = await pool.execute('select * from aluno');
  
  for (final row in result.rows) {
    print(row.assoc());
  }

  print('end of program');
}

执行输出

{id: 2, nome: asd}
{id: 11, nome: ASDAS}
{id: 12, nome: ASDAS}
{id: 13, nome: ASDAS}
{id: 14, nome: ASDAS}
end of program

问题原因

数据库连接池会维持一定数量的活跃连接,这些连接依赖的事件循环任务会阻止Dart程序自动退出——即使主函数的代码执行完毕,连接池后台的连接仍在运行,导致程序无法终止。

解决方案

在程序执行完成后,主动关闭连接池,并等待关闭操作完成,确保所有数据库连接都被释放。

修改后的代码示例:

import 'package:mysql_client/mysql_client.dart';

Future<void> main() async {
  final pool = MySQLConnectionPool(
      host: '127.0.0.1',
      port: 13306,
      userName: 'root',
      password: 'password',
      databaseName: 'dart_mysql',
      maxConnections: 10);

  try {
    var result = await pool.execute('select * from aluno');
    
    for (final row in result.rows) {
      print(row.assoc());
    }
  } finally {
    // 关闭连接池,等待所有连接释放
    await pool.close();
  }

  print('end of program');
}

使用try/finally块可以保证无论数据库操作是否发生异常,连接池都会被关闭。await pool.close()会等待连接池中的所有连接都被正确释放,此时Dart的事件循环没有活跃任务,程序就会自动终止。

内容的提问来源于stack exchange,提问作者Dario Camargo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 05:05:24