5

当我在node.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");
        }
    });
});
4

1 回答 1

6

通常,您重用连接而不是一直打开/关闭。

要回答您的问题,方法如下:

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();
});
于 2013-10-24T10:59:51.840 回答