node.js mysql无法插入

时间:2021-12-21 15:48:12

I'm messing around with node.js, using the Faker, underscore, mysql and randy libraries to add some test data to a web app.

我正在搞乱node.js,使用Faker,下划线,mysql和randy库将一些测试数据添加到Web应用程序。

So far so good-- but in one of my loops, the mysql call fails every time, but it also fails to generate any errors. I'm a bit stumped:

到目前为止这么好 - 但在我的一个循环中,mysql调用每次都失败,但它也无法生成任何错误。我有点难过:

var sql = 'SELECT id FROM mytable WHERE 1';
client.query(sql, function(err, rows, fields){
    // loop through results
    _.each(rows, function (v, i){
        // get the insert id
        var id = v.id; 
        console.log (id); // prints valid ID            
        // generate other data
        var stuff_count = randy.randInt(0,12);
        _(stuff_count).times(function(n){
            var sql = 'INSERT INTO other_table (linked_id, item_id) VALUES ('+id+','+randy.randInt(1,50)+')';
            console.log(sql); // prints sql
            client.query(sql, function(err, rows, fields) {
              console.log(sql); // prints nothing
              if (err){
                console.log(sql); // prints nothing
                throw err; // prints nothing
              }
        });
    });
});

The looping logic is working fine and it gets all the way to where the sql should execute the INSERT against the other_table-- but tailing the mysql log shows nothing hitting the DB, and none of the debug statements inside the client.query block are printing anything, on success or failure.

循环逻辑工作正常,它一直到sql应该对other_table执行INSERT的位置 - 但是后面的mysql日志显示没有任何东西击中DB,而client.query块中的调试语句都没有打印成功或失败的任何事情。

1 个解决方案

#1


0  

assuming you are just running this standalone, your code probably finishes before it has a chance of doing the inserts.

假设您只是运行此独立程序,您的代码可能在它有可能执行插入之前完成。

place a setTimeout(..., 10000) after the _(stuff_count).times(...)

在_(stuff_count).times(...)之后放置一个setTimeout(...,10000)

By using _().times(), you queue all the inserts, but are not waiting for completion. you should use a control flow library to ensure you wait for all inserts to complete.

通过使用_()。times(),您可以对所有插入进行排队,但不等待完成。您应该使用控制流库来确保等待所有插入完成。

#1


0  

assuming you are just running this standalone, your code probably finishes before it has a chance of doing the inserts.

假设您只是运行此独立程序,您的代码可能在它有可能执行插入之前完成。

place a setTimeout(..., 10000) after the _(stuff_count).times(...)

在_(stuff_count).times(...)之后放置一个setTimeout(...,10000)

By using _().times(), you queue all the inserts, but are not waiting for completion. you should use a control flow library to ensure you wait for all inserts to complete.

通过使用_()。times(),您可以对所有插入进行排队,但不等待完成。您应该使用控制流库来确保等待所有插入完成。