从“查询内部查询”结束连接错误
我正在使用mysql节点模块,并有一个错误的Error: Cannot enqueue Query after invoking quit.
从我的源代码有一个块'更新如果存在,否则插入'(类似的逻辑,在我问另一个问题 )。
我将它包含在节点中的原因是“重复”的定义是自定义的。
我已经testing了我的源代码,它能够成功地执行'更新如果存在,否则插入'我的表,但我无法closures我的连接,因为我的插入/更新查询驻留在search查询中。
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(); }
sqlInsert
和sqlUpdate
是在其他地方定义的,并且使用类似于上面的函数的connection.query(..)
定义了sql查询。
我明白, connection.query(..)
是asynchronous的,我把我的connection.end()
在函数的最后。 但我不明白为什么我每次调用我的insertQueue
Cannot enqueue Query after invoking quit
仍然Cannot enqueue Query after invoking quit
错误。
另外如果我replace我的sqlInsert(...);
和sqlUpdate(...)
与一些testing命令(没有数据库SQL查询执行),错误将消失。
这有什么理由吗?
首先你不应该在循环内调用asynchronous函数(map,forEach,for,while或任何人)。 其次,在循环中触发查询是最糟糕的主意。
mysql.js提供从官方文档https://github.com/mysqljs/mysql批量插入的方法
嵌套数组变成分组列表(用于批量插入),例如[['a','b'],['c','d']]变成('a','b'),('c ','d')
举一个例子
connection.query('INSERT INTO posts SET ?', [['a', 'b'], ['c', 'd']], function (error, results, fields) { if (error) throw error; // ... });
第三我认为lastRun是date时间。 你可以selectmysqltypes的当前时间戳,现在不需要担心这个查询,