模式切换
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_timeout
或 wait_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)