Node Mysql Cannot Enqueue a query after calling quit

半城伤御伤魂 提交于 2020-01-31 02:35:03

问题


where do i close the mysql connection?

I need to run queries in sequence. I am writing code that looks like this at present:

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

(I am a beginner with node, npm-express and npm-mysql. I have tried searching SO for "express mysql cannot enqueue" to find related questions and have not found them.)


回答1:


I fixed this problem use this method.

connection.end() in your connection.query function

The fixed code is here




回答2:


If you're using the node-mysql module by felixge then you can call connection.end() at any point after you've made all of the connection.query() calls, since it will wait for all of the queries to finish before it terminates the connection.

See the example here for more information.

If you're wanting to run lots of queries in series, you should look into the async module, it's great for dealing with a series of asynchronous functions (i.e. those that have a callback).




回答3:


Maybe the problem is that the mySQL query is executed after the connection is already closed, due to the asynchronous nature of Node. Try using this code to call connection.end() right before the thread exits:

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

Code adapted from @Emil Condrea, doing a cleanup action just before node.js exits




回答4:


In my case connection.end was being called in a spot that was hard to notice, so an errant call to connection.end could be the problem with this error



来源:https://stackoverflow.com/questions/14333272/node-mysql-cannot-enqueue-a-query-after-calling-quit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!