【问题标题】:How to get json object with multiple rows如何获取具有多行的json对象
【发布时间】:2015-10-20 16:38:49
【问题描述】:

我的目标是将下面 JSON 对象中的Fields 写入 MySQL 数据库。

var dataRow = {
    Table: "promosbudget",
    Fields:[{
        ManagerID: "Jose",
        UserID: "ife",
        Budget: "50000",
        Year: "2015"
    },
    {
        ManagerID: "Jose",
        UserID: "fgs",
        Budget: "50000",
        Year: "2015"
    },
    {
        ManagerID : "Jose",
        UserID : "brz",
        Budget : "50000",
        Year : "2015"
    }]
};

我正在使用这个命令来接收和写入数据:

app.post('/paramsjson', jsonParser, function(req, res) { 
    conMySQL.query('INSERT INTO ' + req.body.Table + ' SET ?',req.body.Fields,               
                 function(err,result) {
            console.log(result);
        }
    );
});

问题是我只能写第一行JSON,其他2行被省略了。

我想问一下,当我需要导出一个大的 JSON 对象(100.000 行)时,是否有推荐的方法来做到这一点,是否需要循环并顺序读取每一行?

提前感谢您的帮助!

【问题讨论】:

  • 你很容易受到sql injection attacks的攻击,需要循环json数据结构并单独插入每个“字段”子对象。

标签: mysql json node.js


【解决方案1】:

尝试一步一步来。 不要直接插入数据库, 首先 console.log 输出,查看结果,尝试直接从代码中插入。然后尝试将它们结合起来。

无论如何 - 我强烈建议将 knex 用于任何数据库操作。

拿这个示例代码进行测试:

app.post('/paramsjson', jsonParser, function(req, res) { 

  console.log(req.body);

  var table = req.body.Table;
  var fields = req.body.Fields;

  //If you want to use knex:

  knex( table ).insert( fields )

    .then(function (result) {
      console.log(result)
    })
    .catch(function (err) {
      console.log(err)
    })

  });

【讨论】:

  • 非常感谢您的 cmets。这很有趣,我会看看这个。
猜你喜欢
  • 2020-12-18
  • 1970-01-01
  • 1970-01-01
  • 2021-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-14
  • 1970-01-01
相关资源
最近更新 更多