当我关闭 node.js 中的数据库连接时,我收到此错误
调用退出后无法将查询排入队列
。
这是我的代码
socket.on('adminConnect', function (email) {
connection = mysql.createConnection(db_config); // db_config has all details of database
connection.connect(); // no problem in connection
connection.query("SELECT id FROM user WHERE email = '" + email + "' ", function (err, results, fields) {
if (err) throw err;
if (results[0]) {
// Some code
connection.end(); // its giving error "Cannot enqueue Query after invoking quit."
} else {
console.log("no id");
}
});
});
最佳答案
一般来说,您会重复使用连接,而不是一直打开/关闭。
要回答您的问题,方法如下:
connection.end();
尝试将该行放在回调之外,因为所有查询都必须在结束连接之前完成,这样就安全了:
connection.query(.......);
connection.end();
您的代码将是:
socket.on('adminConnect', function (email) {
connection = mysql.createConnection(db_config); // db_config has all details of database
connection.connect(); // no problem in connection
connection.query("SELECT id FROM user WHERE email = '" + email + "' ", function (err, results, fields) {
if (err) throw err;
if (results[0]) {
// Some code
} else {
console.log("no id");
}
});
connection.end();
});
关于javascript - 如何在node.js中关闭数据库连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19563474/