使用基础node.js的express框架在连接数据库的过程中,出现Error: Cannot enqueue Handshake after invoking quit.的解决方案
转载声明:
本文为摘录自“csdn博客”,版权归原作者所有。
温馨提示:
为了更好的体验,请点击原文链接进行浏览
摘录时间:
2021-08-06 20:25:24
使用基础node.js的express框架在连接数据库的过程中,出现Error: Cannot enqueue Handshake after invoking quit.的解决方案
情形如下:
在第一次连接数据库的时候,没有问题。第二次连接时候直接断开连接,并报以上错误。
原因是:在请求数据库时,发出connection.connect(),且每次都会connection.end()。但是mysql.createConnection却仅仅只创建了一次。下一次请求的时候并未创建新的连接。
解决方案
- 最简单的解决方案是直接去掉connection.end(),这样可以保证让让数据库自己释放不活跃的连接。
- 思路是每次连接均创建新的createConnection。具体思路如下:
dbsava.js
var mysql = require('mysql');
class Connect {
constructor()
{
this.str = '';
this.connection;
}
//创建新的连接
CreateNewConnection()
{
this.connection = mysql.createConnection({
host: 'localhost',
port: '3306',
user: 'root',
password: '0610',
database: 'myemployees'
});
}
//查询数据接口
LookupMessage = function(sql,callback) {
this.CreateNewConnection();
let connection = this.connection;
connection.connect();
connection.query(sql, function (err, result) {
if (err) {
console.log('[SELECT ERROR]:', err.message);
}
this.str = result;
callback(this.str);
connection.end();
})
}
}
module.exports = { Connect }
index.js
httpServer.get('/getMessage',(req,res)=>{
Req.LookupMessage("SELECT * FROM employees",results=>{
console.log("getMessage接口响应", new Date().toLocaleTimeString());
res.send({code:0,results});
});
})