如何在node.js中关闭数据库连接?

时间:2013-10-24 10:32:13

标签: javascript node.js

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

1 个答案:

答案 0 :(得分:1)

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

要回答您的问题,请按照以下方式:

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