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

标签 javascript node.js

当我关闭 node.js 中的数据库连接时,我收到此错误

调用退出后无法将查询排入队列

这是我的代码

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

关于javascript - 如何在node.js中关闭数据库连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19563474/

相关文章:

javascript - 使用js和css无限顺时针旋转 - timeout(0) 和 requestAnimationFrame() 之间的区别

javascript - Promise.all 不适用于异步内部函数

node.js - 运行 Electron 应用程序时出现错误时我能做什么

javascript - 动态引用导入

javascript - 我可以向构建时创建的脚本标签添加属性吗?

javascript函数可进行两次调用但只运行一次

jquery - Node.js JSON.stringify() 在输出中导致“。无法使用 Jquery 解析

javascript - React Router v6.0.0-alpha.5 历史 Prop 删除 - 在 react 上下文之外导航

node.js - Node js可以进行restful服务调用吗

javascript - 使用全局变量来防止代码不必要地重复执行