【问题标题】:node.js mysql failing to insertnode.js mysql无法插入
【发布时间】:2013-01-29 04:07:45
【问题描述】:

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

到目前为止一切顺利——但在我的一个循环中,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
              }
        });
    });
});

循环逻辑工作正常,它一直到 sql 应该针对 other_table 执行 INSERT 的位置——但是跟踪 mysql 日志显示没有任何内容触及数据库,并且内部没有任何调试语句client.query 块正在打印任何内容,无论成功还是失败。

【问题讨论】:

  • 不要忘记对注入 SQL 的值使用 connection.escape()
  • @tadman-- 谢谢,我在数据不是整数的地方这样做。
  • 这是一个风格点,但你应该尝试摆脱回调地狱:P

标签: javascript mysql node.js


【解决方案1】:

假设您只是单独运行此程序,您的代码可能会在有机会进行插入之前完成。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-14
    • 1970-01-01
    相关资源
    最近更新 更多