如何closuresnode.js中的数据库连接?

当我closuresnode.js中的数据库连接时,我得到这个错误

Cannot enqueue Query after invoking quit

这是我的代码

 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"); } }); }); 

一般来说,您可以重复使用连接,而不是一直打开/closures。

要回答你的问题,这是如何:

 connection.end(); 

试着把这一行放在callback之外,因为在结束一个连接之前所有的查询都必须完成,所以你是这样安全的:

 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(); });