Nodejs多个sql查询循环

时间:2016-06-15 08:28:00

标签: mysql node.js

我对nodejs和异步世界都很陌生。

案例是,我有一个像var ids = [1, 2, 3, 4];

这样的数组

我需要根据数组元素的顺序更新mytable。所以我做了类似的事情:

sort: function(ids, callback) {

 // dont worry about this
  this.create_connection();
  this.connection.connect();

   for(var i=0; i<ids.length;i++) {
      var q = "UPDATE mytable SET sequence="+i+" where id="+ids[i]+"; ";

      this.connection.query(q, function(err, result) {

       // I am not sure about this
       // callback(err);
     });
   }

 // I need to return callback at the end
 // return callback();

  this.connection.end();

}

但是是..它不起作用,因为我必须返回回调..我想我需要同步进行查询..我不确定。请帮助谢谢。

2 个答案:

答案 0 :(得分:2)

如果您不熟悉异步世界,则应该查看模块&#39; async&#39;。

然后你可以这样做:

async.forEachOfSeries(ids, function(id,index,callback){
     var q = "UPDATE mytable SET sequence="+index+" where id="+id+"; ";

      this.connection.query(q, function(err, result) {         
         callback();
     });


},function done(){
    // whatever you want to do onces all the individual updates have been executed.
})

答案 1 :(得分:0)

请参阅我的内联评论:

import scipy as sp
p = 0.2
sp.random.binomial(1, p)

这里有点优雅:

sort: function(ids, callback) {
  this.create_connection();
  this.connection.connect();
  var q = "UPDATE mytable SET sequence CASE id ";

  // Don't execute one query per index in ids - that's inefficient
  // Instead, pack up all the queries and execute them at once
  for(var i=0; i<ids.length;i++) {
    q += "WHEN " + ids[i] + " THEN " + i + " ";
  }
  q += "ELSE sequence END;";

  // The sort method will return the result of connection.query
  return this.connection.query(q, function(err, result) {
    // End the connection
    this.connection.end();
    if(err) {
      // Handle any error here
      return callback(err);
    }
    // Otherwise, process, then return the result
    return callback(err, result);
  });
}

如果您想使用ES6箭头功能,可以使用以下内容替换上一个示例中的sort: function(ids, callback) { this.create_connection(); this.connection.connect(); // Don't execute one query per index in ids - that's inefficient // Instead, pack up all the queries and execute them at once var q = ids.reduce(function(pv, cv, ci){ return pv + " WHEN " + cv + " THEN " + ci + " "; }, "UPDATE mytable SET sequence CASE id ") + " ELSE sequence END;"; // The sort method will return the result of connection.query return this.connection.query(q, function(err, result) { // End the connection this.connection.end(); if(err) { // Handle any error here return callback(err); } // Otherwise, process, then return the result return callback(err, result); }); }

.reduce