Skip to content

Express 连接 MySQL 报错:Connection lost: The server closed the connection.

【问题】

Express 连接 MySQL 报错:

bash
MySQL error: Error: Connection lost: The server closed the connection.
    at Protocol.end (/Users/hayden/Desktop/ProjectDevelopment/2024-12-31-01/ExpressServerDemo/node_modules/mysql/lib/protocol/Protocol.js:112:13)
    at Socket.<anonymous> (/Users/hayden/Desktop/ProjectDevelopment/2024-12-31-01/ExpressServerDemo/node_modules/mysql/lib/Connection.js:94:28)
    at Socket.<anonymous> (/Users/hayden/Desktop/ProjectDevelopment/2024-12-31-01/ExpressServerDemo/node_modules/mysql/lib/Connection.js:526:10)
    at Socket.emit (node:events:531:35)
    at endReadableNT (node:internal/streams/readable:1696:12)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
  fatal: true,
  code: 'PROTOCOL_CONNECTION_LOST'
}
Connected to MySQL

【解决方案一】

如果你使用的是 MySQL 8.x 及以上版本,请更换至 MySQL 5.x 版本。

【解决方案二】

报错重连:判断报错 code==='PROTOCOL_CONNECTION_LOST' 时重新连接。

javascript
this.connection.on('error', err => {
    if (err.code === 'PROTOCOL_CONNECTION_LOST') {
        log.error('mysql error ===> PROTOCOL_CONNECTION_LOST')
        this.init()
    }
})

【解决方案三】

设置 MySQL 的 interactive_timeoutwait_timeout。通过命令的方式执行或者直接打开并修改 my.cnf 文件。

bash
mysql> set global wait_timeout=864000;
Query OK, 0 rows affected (0.00 sec)

若无效,则继续设置 interactive_timeout

bash
mysql> set global interactive_timeout=864000;
Query OK, 0 rows affected (0.00 sec)
bash
mysql> SHOW GLOBAL VARIABLES LIKE '%timeout%';
+-----------------------------+----------+
| Variable_name               | Value    |
+-----------------------------+----------+
| connect_timeout             | 10       |
| delayed_insert_timeout      | 300      |
| have_statement_timeout      | YES      |
| innodb_flush_log_at_timeout | 1        |
| innodb_lock_wait_timeout    | 120      |
| innodb_rollback_on_timeout  | OFF      |
| interactive_timeout         | 864000   |
| lock_wait_timeout           | 31536000 |
| net_read_timeout            | 30       |
| net_write_timeout           | 60       |
| rpl_stop_slave_timeout      | 31536000 |
| slave_net_timeout           | 60       |
| wait_timeout                | 864000   |
+-----------------------------+----------+
13 rows in set (0.00 sec)
编程洪同学服务平台是一个广泛收集编程相关内容和资源,旨在满足编程爱好者和专业开发人员的需求的网站。无论您是初学者还是经验丰富的开发者,都可以在这里找到有用的信息和资料,我们将助您提升编程技能和知识。
专业开发
高端定制
售后无忧
站内资源均为本站制作或收集于互联网等平台,如有侵权,请第一时间联系本站,敬请谅解!本站资源仅限于学习与参考,严禁用于各种非法活动,否则后果自行负责,本站概不承担!