节点Mysql在调用quit之后无法排队查询

我在哪里closuresmysql连接?

我需要按顺序运行查询。 我现在正在编写这样的代码:

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

(我是一个初学者,有npm-express和npm-mysql,我试过search“express mysql can not enqueue”find相关的问题,但是没有find它们。)

我使用这种方法解决了这个问题。

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

固定代码在here

如果你通过felixge使用node-mysql模块,那么在完成所有的connection.query()调用之后,你可以随时调用connection.end(),因为它将等待所有的查询完成在它终止连接之前。

有关更多信息,请参阅此处的示例 。

如果你想要串行运行大量的查询,你应该看看asynchronous模块 ,这对于处理一系列asynchronous函数(也就是那些有callback的)来说是非常好的。

也许问题是,由于Node的asynchronous性质,在连接已经closures之后执行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编写, 在node.js退出之前执行清理操作

在我的情况connection.end被称为一个难以注意的地方,所以一个错误的调用connection.end可能是这个错误的问题