javascript Node.js 和 mysql 回调:在查询回调中查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16134378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 03:23:08  来源:igfitidea点击:

Node.js and mysql Callback : query in query callback

javascriptmysqlnode.jsnode-mysql

提问by Arvin

All I want to do is insert some data if my database doesn't have that, so I put Insert SQL into my callback function of my Select SQL, but I got error like this:

如果我的数据库没有,我想要做的就是插入一些数据,所以我将 Insert SQL 放入我的 Select SQL 的回调函数中,但是我得到了这样的错误:

{ [Error: Cannot enqueue Query after invoking quit.] code: 'PROTOCOL_ENQUEUE_AFTER_QUIT', fatal: false }

{ [错误:调用退出后无法入队查询。] 代码:'PROTOCOL_ENQUEUE_AFTER_QUIT',致命:假}

my code snippet is here:

我的代码片段在这里:

db.query('SELECT count(*) as Resultcount FROM tablename WHERE email = ? and password = ?', [post.email, post.password], function(error, result){
    if (result[0].Resultcount == 0){
        var query2 = db.query('INSERT INTO tablename SET ?', [post], function(err, result) {
            if(err){
              console.log(err);
           }
             console.log(result);
          });
    }
    else{
        console.log('have data already');
    }
});

Could someone give me some advice? Thanks

有人能给我一些建议吗?谢谢

----update----

- - 更新 - -

actually, the callback function of select SQL is not an anonymous function, my code snippet about db.end() is like this:

其实select SQL的回调函数不是匿名函数,我的db.end()代码片段是这样的:

var QueryResults = new queryResultFuntion(Back_results);

    db.query('SELECT count(*) as Resultcount FROM tablename WHERE email = ? and password = ?', [post.email, post.password], QueryResults.queryResult );


    db.end();

回答by loganfsmyth

You db.end()call will queue the connection to close once the SELECThas completed, so when you attempt to do the inner INSERTquery, the database connection will have been closed, hence the error PROTOCOL_ENQUEUE_AFTER_QUIT, as you are attempting to queue a new command after the connection is closed.

db.end()一旦SELECT完成,您调用将使连接排队关闭,因此当您尝试执行内部INSERT查询时,数据库连接将已关闭,因此错误 PROTOCOL_ENQUEUE_AFTER_QUIT,因为您试图在连接关闭后将新命令排队.

Depending on how you are creating the connection, you should either move your db.end()call inside the callbacks, or not have a db.end()call at all if the connection is opened on program start.

根据您创建连接的方式,您应该db.end()在回调中移动您的调用,或者db.end()如果在程序启动时打开连接,则根本不调用。