使用NodeJS将JSON插入MySQL JSON列格式

时间:2017-07-25 08:25:45

标签: javascript mysql angularjs json node.js

我有一个包含这些设置的Mysql表:

    CREATE TABLE `WorkOrders` (
  `workorder_id` int(11) NOT NULL AUTO_INCREMENT,
  `intertype_id` int(11) NOT NULL,
  `equipment_id` int(11) NOT NULL,
  `reason_id` int(11) NOT NULL,
  `requester_id` int(11) NOT NULL,
  `workorder_creationdatetime` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `phase_id` int(11) NOT NULL,
  `criticality_id` int(11) NOT NULL,
  `workorder_targetdate` date DEFAULT NULL,
  `workorder_enddatetime` datetime DEFAULT NULL,
  `workorder_content` json DEFAULT NULL,
  PRIMARY KEY (`workorder_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

列' workorder_content'有一个JSON数据类型。

然后我使用NodeJS api将AngularJS + Bootstrap链接到数据库。

我正在尝试使用该脚本将数据插入到我的表中:

connection.acquire(function(err, con) {
      con.query('INSERT INTO WorkOrders SET ?', workorder.workorder.int, function(err, result) {
        con.release();
        console.log(err);
        if (err) {
          res.send({status: 1, message: 'WorkOrder creation failed'});
        } else {
          res.send({status: 0, message: 'WorkOrder created successfully'});
        }
      });
    });

以下是workorder.workorder.int包含的内容:

{ phase_id: 1,
  intertype_id: '14',
  reason_id: '1',
  equipment_id: '2',
  requester_id: '24',
  criticality_id: '29',
  workorder_content: 
   { adresse_client: 'sefsdf',
     type_machin: '1',
     type_truc: '8',
     truc_cocher: true,
     truc_radio: '11',
     date_debut: '12/07/2017' } }

我在NodeJS控制台中遇到的错误是: {错误:UNKNOWN_CODE_PLEASE_REPORT:无效的JSON文本:"无效的值。"在值(或列)中的位置1' [对象对象]'。

你能帮帮我吗?

谢谢。

2 个答案:

答案 0 :(得分:3)

您正在发送一个名为'[object Object]'的字符串。到MySQL而不是对象。请尝试以下方法:

connection.acquire(function(err, con) {
      con.query('INSERT INTO WorkOrders SET ?', JSON.stringify(workorder.workorder.int), function(err, result) {
        con.release();
        console.log(err);
        if (err) {
          res.send({status: 1, message: 'WorkOrder creation failed'});
        } else {
          res.send({status: 0, message: 'WorkOrder created successfully'});
        }
      });
    });

答案 1 :(得分:-1)

感谢响尾蛇,我找到了解决方案。

这是:

button

因此需要对将插入到MySQL中的JSON列而不是整个JSON对象的部分进行字符串化。