每个循环中嵌套的mysql查询

时间:2015-09-02 10:44:56

标签: mysql node.js asynchronous underscore.js

所以我想做的就是进行查询以从数据库中获取所有id,然后我想为id执行我的方法并更新数据库中的行。

所以我创建了这段代码。但它所做的只是获取id而不是嵌套查询与insertString1。

var mysql = require('mysql');
var _ = require("underscore");
var connection = mysql.createConnection({
    host     : 'myHost.net',
    user     : 'myUser',
    password : 'myPassword',
    database : 'myDatabase'
});


connection.query('SELECT * FROM `idmarkethash`', function (error, results) {
    _.each(results, function (row) {
        // here i want to calculate the new values of the row
        // This insert query is just an example
        var insertString1 = "UPDATE idmarkethash SET " +
                    "Price=" + mysql.escape(2.00) + ", " +
                    "Gradient=" + mysql.escape(2.00) + ", " +
                    "LastUpdated=" + mysql.escape("2015-08-31 00:00:11") + " " + 
                    "WHERE Id=" + mysql.escape(181) + ";";
        connection.query(insertString1, function (error1, result1) {
            console.log(result1);
        });    
    });
});

我尝试使用异步包:

var async = require('async');
// Packages are all included.

connection.query('SELECT * FROM `idmarkethash`', function (error, results) {
    async.each(results, function (row, callback) {
        // here i want to calculate the new values of the row
        // This insert query is just an example
        var insertString1 = "UPDATE idmarkethash SET " +
                    "Price=" + mysql.escape(2.00) + ", " +
                    "Gradient=" + mysql.escape(2.00) + ", " +
                    "LastUpdated=" + mysql.escape("2015-08-31 00:00:11") + " " + 
                    "WHERE Id=" + mysql.escape(181) + ";";
        connection.query(insertString1, function (error1, result1) {
            console.log(result1);
            callback();
        });    
    });
});

通过调试我可以看到insertString1的声明被调用,但第二个查询没有被触发/或循环继续而没有识别第二个查询。

0 个答案:

没有答案