【问题标题】:node mysql insert and select count not working节点mysql插入和选择计数不起作用
【发布时间】:2016-06-11 07:18:31
【问题描述】:

我在node.js 中使用了两个函数function1function2

function1用于向表中插入数据。

for(var j=0; j < length; j++){

   connection.query('INSERT INTO TestTable SET ?', { row_name : name }, function(err, res){
      if(err) throw err;
   });
}

function2用来选择插入名字的个数,count。

connection.query('select row_name, count(*) as count from TestTable where row_name = ?', name , function (err, rows){  
    console.log(rows);
}); 

我的log 给了我name : null, count : 0

我做错了什么?

【问题讨论】:

    标签: node.js mysql2


    【解决方案1】:

    首先,在循环中运行 mysql 查询是一种不好的做法。第二, 你错过了 javascript 中异步流的基础知识。 Here 是一篇很好的文章,其中解释了 JavaScript 中异步编程的基本概念。 connection.query 是异步的,所以如果你想让你的代码工作,你应该在最后一次迭代的插入查询的回调中运行计数查询。

    但正如我已经提到的,循环运行它们是一种不好的做法。我建议您只在循环中为多个插入构建查询字符串,但最后只运行一次(在回调中使用计数查询)。

    【讨论】:

      猜你喜欢
      • 2017-01-22
      • 2018-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-17
      • 2023-03-13
      • 2012-07-01
      • 2014-03-03
      相关资源
      最近更新 更多