嵌套的SQL查询里面的循环node.js不工作

我有一个for循环通过一个JSON数组 – 在这个堆栈问题的帮助

循环脚本会执行以下操作:

- Does the JSON item exist in the tables? - if yes - Is the data different? - if yes - Update - if no - Do nothing - if no -insert into database 

我发现这个问题,允许我查询每个循环,所以我能够从JSON中获取名称,并正确地查询它们:

 for(var i=0; i<content.prices.length; i++) { var price = content.prices[i].price var itemName = content.prices[i].market_hash_name; var q = "SELECT * FROM prices WHERE item = ?"; (function() { var iNameCopy = itemName; var priceCopy = price; connection.query(q, iNameCopy, function (err, results) { if (err) throw err; if(results.length === 1) { logger.info(iNameCopy + " does exist"); } else if (results.length === 0){ logger.info(iNameCopy + " does not exist"); } }); }()); } 

移动到results.length === 1添加if语句results.length === 1

 for(var i=0; i<content.prices.length; i++) { var price = content.prices[i].price var itemName = content.prices[i].market_hash_name; var q = "SELECT * FROM prices WHERE item = ?"; (function() { var iNameCopy = itemName; var priceCopy = price; connection.query(q, iNameCopy, function (err, results) { if (err) throw err; if(results.length === 1) { if(parseFloat(results[0].current_price) != parseFloat(priceCopy)) { logger.info(iNameCopy + " does exist with old price: " + results[0].current_price + " and new price: " + priceCopy); } } else if (results.length === 0){ logger.info(iNameCopy + " does not exist"); } }); }()); } 

这仍然是工作。

现在最后用新的sql查询代替logging器就是代码绊倒的地方。 for循环运行,就像我保持他们显示的logging器,但sql查询logging器不显示:

我尝试了这两种方法,我发现从另一个堆栈问题,没有包装在一个函数,但都没有工作。 有什么build议么?

 for(var i=0; i<content.prices.length; i++) { var price = content.prices[i].price var itemName = content.prices[i].market_hash_name; var q = "SELECT * FROM prices WHERE item = ?"; (function() { var iNameCopy = itemName; var priceCopy = price; connection.query(q, iNameCopy, function (err, results) { if (err) throw err; if(results.length === 1) { if(parseFloat(results[0].current_price) != parseFloat(priceCopy)) { var sql2="UPDATE `prices` SET `current_price` = ?, `timeStamp` = ? WHERE `item` = ?"; (function() { var iNameCopy2 = iNameCopy var priceCopy2 = priceCopy connection.query(sql2, [priceCopy2, 'Now()', iNameCopy2], function(err,results){ logger.info("UPDATE: " + iNameCopy2 + ' has been updated with price ' + priceCopy2); }); }()); } } else if (results.length === 0){ var sql3="INSERT INTO `prices` (`item`, `current_price`, `timeStamp`) VALUES (?, ?, ?)"; (function() { var iNameCopy3 = iNameCopy var priceCopy3 = priceCopy connection.query(sql3, [iNameCopy3, priceCopy3, 'Now()'], function(err,results){ logger.info("INSERT: " + iNameCopy3 + ' has been added with price ' + priceCopy3); }); }()); } }); }()); } 

注意:我有for循环的外部我的数据库连接:

 var connection = mysql.createConnection(db_access); connection.connect(function(err){ if(err){ logger.error('Error connecting to Db'); return; } }); 

       

网上收集的解决方案 "嵌套的SQL查询里面的循环node.js不工作"