javascript 如何关闭 node.js 中的数据库连接?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19563474/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to close database connection in node.js?
提问by Vardan
When i am closing database connection in node.jsi am getting this error
当我在node.js 中关闭数据库连接时出现此错误
Cannot enqueue Query after invoking quit
.
Cannot enqueue Query after invoking quit
.
Here is my code
这是我的代码
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");
}
});
});
采纳答案by randunel
In general, you reuse connections instead of opening/closing all the time.
通常,您重用连接而不是一直打开/关闭。
To answer your question, this is how:
要回答您的问题,方法如下:
connection.end();
Try putting the line outside the callback, because all the queries must complete before ending a connection, so you're safe like this:
尝试将该行放在回调之外,因为所有查询都必须在结束连接之前完成,因此您可以像这样安全:
connection.query(.......);
connection.end();
Your code would then be:
您的代码将是:
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();
});