从查询中查询'

时间:2017-12-10 04:00:48

标签: mysql node.js

我正在使用mysql节点模块,并且我的源代码出现Error: Cannot enqueue Query after invoking quit.错误,如果存在,则会有一个更新的块,否则插入' (与我提出的another question中的逻辑相似)。

我将其包含在节点中的原因是'复制'的定义。是定制的。

我测试了我的源代码,如果存在,它能够成功执行更新,否则插入'到我的表,但我无法关闭我的连接,因为我的插入/更新查询驻留在搜索查询中。

const insertQueue = (results) => {
  _.forEach(results, (values, key) => {
    _.map(values, (value) => {
      let query = 'SELECT index FROM table WHERE (document=? AND ((document NOT like \'PERSONAL:%\' AND username=?) OR (document like \'PERSONAL:%\' AND serial=?)))';
      connection.query(query, [value.document, key, value.serial], function(error, rows){
        if (error) {
          console.log(error);
        }
        else {
          //Ideally there should be only one entry, but still return an array to make the function error-safe
          let indices = _.map(rows,'index');
          if (_.isEmpty(indices)) {
            //sqlInsert and sqlUpdate are defined elsewhere and has sql query defined with 'connection.query(..)' similar to this
            sqlInsert(key, value.serial, value.document, value.lastRun);
          }
          else {
            _.each(indices, (index) => {
              sqlUpdate(index,value.lastRun);
            });
          }
        }
      });
    });
  });
  connection.end();
}

sqlInsertsqlUpdate在其他地方定义,并且使用类似于上述函数的connection.query(..)定义了sql查询。

我理解connection.query(..)是异步的,我将connection.end()放在函数的最后。但我不明白为什么每次拨打Cannot enqueue Query after invoking quit时我仍然会收到insertQueue的错误。

此外,如果我用一些测试命令替换我的sqlInsert(...);sqlUpdate(...)(没有执行db sql查询),错误将会消失。

这有什么理由吗?

1 个答案:

答案 0 :(得分:1)

首先你不应该在循环内调用异步函数(map,forEach,for,while或者任何人)。 第二,在循环中触发查询是最糟糕的主意。

mysql.js提供批量插入的方法 来自官方文件https://github.com/mysqljs/mysql

  

嵌套数组转换为分组列表(对于批量插入),例如   [[' a',' b'],[' c'' d']]变成了(' a&# 39;,' b'),(' c',' d')

举个例子

connection.query('INSERT INTO posts SET ?', [['a', 'b'], ['c', 'd']], function (error, results, fields) {
  if (error) throw error;
  // ...
});

第三,我认为lastRun是datetime。你可以选择mysql类型的当前时间戳,现在无需担心这个问题,