如何获取多行的json对象

时间:2015-10-20 16:38:50

标签: mysql json node.js

我的目标是将下面的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,其他两行都省略。

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

提前感谢您的帮助!

1 个答案:

答案 0 :(得分: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)
    })

  });