从post方法插入多个数组

时间:2019-04-12 16:17:55

标签: mysql node.js express

我正在尝试从邮递员那里获取邮递数据,邮递员是多个数据数组,但似乎无法让它们进入数据库,如果我在邮递上对数组进行硬编码,它将进入数据库,但是不是动态的。

index.js

/* POST home page. */
router.post('/', function (req, res) {
    const sql = require('../models/db.js');

    let data = req.param('data');
    console.log(data);

    const sqlstatement = "INSERT INTO Sales (user_id, type, amount) VALUES (?)";

    sql.query(sqlstatement, [data], function (err, res) {

        if(err) {
            console.log("error: ", err);
        }
        else{
            console.log(res.insertId);
        }
    });

    res.send(data);

});

db.js



'user strict';

const mysql = require('mysql');

//local mysql db connection
let connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : '',
    database : 'api'
});

connection.connect(function(err) {
    if (err) throw err;
});

module.exports = connection;

邮递员数据

[{"key":"data","value":"[[111, 'net', 1234],[111, 'gross', 1234]]\n","description":"","type":"text","enabled":true}]

控制台错误


code: 'ER_BAD_FIELD_ERROR',
  errno: 1054,
  sqlMessage:
   "Unknown column '[[111, 'net', 1234],[111, 'gross', 1234]]' in 'field list'",
  sqlState: '42S22',
  index: 0,
  sql:
   "INSERT INTO Sales (user_id, type, amount) VALUES (`[[111, 'net', 1234],[111, 'gross', 1234]]`)" }

2 个答案:

答案 0 :(得分:0)

const sqlstatement = "INSERT INTO Sales (user_id, type, amount) VALUES (?,?,?)"

您必须在每一列上打一个问号。

答案 1 :(得分:0)

准备适当的SQL语句

INSERT INTO Sales (user_id, type, amount) VALUES (111, 'net', 1234),(111, 'gross', 1234);