Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/42.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在node.js中关闭数据库连接?_Javascript_Node.js - Fatal编程技术网

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

Javascript 如何在node.js中关闭数据库连接?,javascript,node.js,Javascript,Node.js,当我在node.js中关闭数据库连接时,我遇到了这个错误 调用quit后无法将查询排队 这是我的代码 socket.on('adminConnect', function (email) { connection = mysql.createConnection(db_config); // db_config has all details of database connection.connect(); // no problem in connection con

当我在node.js中关闭数据库连接时,我遇到了这个错误

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

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

要回答您的问题,以下是如何:

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

通常,您不希望为每个请求创建新连接。保持连接以获取更多其他查询。好的,我会这样做。但我的问题是在哪里结束连接?@user问题是你没有。为什么要关闭一个可以重用的连接?连接很便宜,但打开它们需要一到三次往返。如果我不再需要使用连接,这个答案是正确的。如果我必须重复使用它,它不需要关闭。谢谢randunel。您不必等待
连接。在调用
connection.end
之前完成查询。应该从
连接中调用它。query
回调。@robertklep如果您在做出错误假设之前花时间浏览文档,您会注意到您可能会在触发回调之前调用
.end()
,因为
关闭连接是使用end()完成的它确保在向mysql服务器发送退出数据包之前执行所有剩余的查询。
-引用节点mysql文档。文档中有一个类似代码的示例。关于重新使用连接,请阅读我回答中的第一段;)@我真的很抱歉,你说得对!我的假设是基于Node的一般思想,即在关闭连接之前必须等待操作的执行,而MySQL在这方面是聪明的。再说一次,对不起!