【问题标题】:Node Mysql Cannot Enqueue a query after calling quit调用退出后,节点 Mysql 无法将查询入队
【发布时间】:2012-12-29 06:54:55
【问题描述】:

在哪里关闭 mysql 连接?

我需要按顺序运行查询。我目前正在编写如下代码:

var sqlFindMobile = "select * from user_mobiles where mobile=?";
var sqlNewUser = "insert into users (password) values (?)";
//var sqlUserId = "select last_insert_id() as user_id";
var sqlNewMobile = "insert into user_mobiles (user_id, mobile) values (?,?)";
connection.connect(function(err){});
var query = connection.query(sqlFindMobile, [req.body.mobile], function(err, results) {
    if(err) throw err;
    console.log("mobile query");
    if(results.length==0) {
        var query = connection.query(sqlNewUser, [req.body.password], function(err, results) {
            if(err) throw err;
            console.log("added user");
            var user_id = results.insertId;
            var query = connection.query(sqlNewMobile, [user_id, req.body.mobile], function(err, results) {
                if(err) throw err;
                console.log("added mobile");
                    //connection.end();
                });
        });
    }
});
//connection.end();

(我是node、npm-express和npm-mysql的初学者。我尝试过搜索“express mysql cannot enqueue”以找到相关问题,但没有找到。)

【问题讨论】:

  • 您应该将您的 connection.end() 调用移到回调中,或者如果在程序启动时打开连接,则根本没有 connection.end() 调用。检查这个答案stackoverflow.com/a/16134471/8111190

标签: mysql node.js express npm


【解决方案1】:

我用这个方法解决了这个问题:

connection.end() 在你的 connection.query 函数中

固定代码是here

【讨论】:

  • 由于 NodeJS 异步 connection.end() 将在执行数据库调用之前触发。
【解决方案2】:

如果您正在使用 felixgenode-mysql 模块,那么您可以在完成所有连接后随时调用 connection.end() .query() 调用,因为它会在终止连接之前等待所有查询完成。

请参阅example here 了解更多信息。

如果您想连续运行大量查询,您应该查看async module,它非常适合处理一系列异步函数(即具有回调的函数)。

【讨论】:

  • 我正在调用 connection.end() 在“添加的移动”日志之后被注释掉的那个。我感觉到的问题是,如果流退出,即在任何 throw(err) 点中,连接将不会关闭。我痛苦地意识到连接被打开是一个新手错误及其对可扩展性的影响。我只是不想在我生命中的这一点上这样做。所以如果你有一个可以遵循的模式,那就太好了。 async 似乎是一个不错的选择。我会花一天时间检查并回复。谢谢。
  • 说到很快,异步对我不起作用,因为这些查询是嵌套的,而不是必须串行执行的东西。维护状态和检查前提条件的开销太大了。
  • 您可以使用瀑布函数来运行查询。我在这里写出了基本结构:pastebin.com/RDaiqZsp
【解决方案3】:

可能问题是由于 Node 的异步特性,mySQL 查询是在连接已经关闭之后执行的。尝试在线程退出之前使用此代码调用 connection.end():

function exitHandler(options, err) {
    connection.end();
    if (options.cleanup)
        console.log('clean');
    if (err)
        console.log(err.stack);
    if (options.exit)
        process.exit();
}

//do something when app is closing
process.on('exit', exitHandler.bind(null, {cleanup: true}));

代码改编自@Emil Condrea,doing a cleanup action just before node.js exits

【讨论】:

    【解决方案4】:

    在我的例子中,connection.end 在一个很难注意到的地方被调用,所以对 connection.end 的错误调用可能是这个错误的问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-18
      • 1970-01-01
      • 2020-03-10
      • 2023-03-21
      • 2017-06-19
      • 2020-03-08
      • 1970-01-01
      • 2021-12-13
      相关资源
      最近更新 更多