Node.js使用mysql2时,如何正确关闭连接避免脚本中断?
解决Node.js中mysql2连接关闭的问题
核心问题分析
你遇到的问题根源在于异步操作未被正确等待:代码里用Array.map()遍历执行异步数据库操作,但map不会等待每个异步函数执行完成,导致await fillTables()执行结束时,内部的INSERT/SELECT操作可能还在后台运行。这时候提前调用connection.end()会中断正在进行的数据库请求引发报错;不关闭连接的话,Node.js进程会因为持有着活跃的数据库连接一直处于等待状态,无法自动退出。
修复方案
- 替换
map为可等待的异步遍历方式:用for...of或者Promise.all()确保所有异步操作执行完毕。 - 在所有操作完成后关闭连接:等
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
相关产品推荐
相关产品推荐

