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

Node.js使用mysql2时,如何正确关闭连接避免脚本中断?

解决Node.js中mysql2连接关闭的问题

核心问题分析

你遇到的问题根源在于异步操作未被正确等待:代码里用Array.map()遍历执行异步数据库操作,但map不会等待每个异步函数执行完成,导致await fillTables()执行结束时,内部的INSERT/SELECT操作可能还在后台运行。这时候提前调用connection.end()会中断正在进行的数据库请求引发报错;不关闭连接的话,Node.js进程会因为持有着活跃的数据库连接一直处于等待状态,无法自动退出。

修复方案

  1. 替换map为可等待的异步遍历方式:用for...of或者Promise.all()确保所有异步操作执行完毕。
  2. 在所有操作完成后关闭连接:等fillTables()执行结束后,再调用connection.end()。

修改后的代码示例

const connection = await mysql.createConnection({
  host: config.host,
  database: config.mysqlMainDatabase,
  user: config.mysqlUser,
  password: config.mysqlPassword
})

const fillTables = async () => {
  const [result_1] = await connection.execute(`SELECT DISTINCT(f_1) FROM t_1`);
  
  // 用for...of替代map,确保每个异步操作按顺序完成
  for (const result_item of result_1) {
    await connection.execute(`INSERT INTO t_2 (f_1) VALUES (?)`, [result_item.m])
    const [result_mm] = await connection.execute(`SELECT DISTINCT(f_2) FROM t_1 WHERE f_1 = ?`, [result_item.m])
    let jsonM = []
    
    // 替换内层map为for...of
    for (const result_m of result_mm) {
      jsonM.push(result_m.mm)
      const [result_ym] = await connection.query(`SELECT DISTINCT(f_3) FROM t_1 WHERE f_1 = ? AND f_2 = ?`, [result_item.m, result_m.mm])
      let jsonY = result_ym.map(result_y => result_y.y)
      await connection.query(`INSERT INTO t_3 (f_1, f_2, f_3) VALUES (?,?,?)`, [result_item.m, result_m.mm, JSON.stringify(jsonY)])
    }
    
    await connection.query(`INSERT INTO t_2 (f_1, f_2) VALUES (?,?)`, [result_item.m, JSON.stringify(jsonM)])
  }
}

// 等待所有数据库操作完成后关闭连接
await fillTables()
await connection.end() // 此时关闭连接不会报错,脚本也能正常退出

效率优化可选方案

如果想并发执行内层异步操作以提升效率,可以用Promise.all()替代for...of,但要注意控制并发数避免触发MySQL连接上限:

// 内层用Promise.all实现并发执行
await Promise.all(result_mm.map(async result_m => {
  jsonM.push(result_m.mm)
  const [result_ym] = await connection.query(`SELECT DISTINCT(f_3) FROM t_1 WHERE f_1 = ? AND f_2 = ?`, [result_item.m, result_m.mm])
  let jsonY = result_ym.map(result_y => result_y.y)
  await connection.query(`INSERT INTO t_3 (f_1, f_2, f_3) VALUES (?,?,?)`, [result_item.m, result_m.mm, JSON.stringify(jsonY)])
}))

内容的提问来源于stack exchange,提问作者Darek Missa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 17:22:38