如何将对象数组插入mysql数据库

zlwx9yxi  于 2023-01-16  发布在  Mysql
关注(0)|答案(3)|浏览(272)

我遇到了一个问题,我有一个像这样的对象数组:

[
  {
    department_id: '6256f8ae6f749617e8167416',
    employee_id: '6253ca0c6f749618a8d022af',
    employee_number: '1234'
  },
  {
    department_id: '6256f8ae6f749617e8167416',
    employee_id_id: '6253ca0c6f749618a8d022af',
    employee_number: '1503'
  }
]

我想用node js和mysql把它插入数据库,所以我有这个脚本

Department.assignEmployeetoDepartment = (employees, result) => {
  let employees_array = Object.values(rooms);

  db.query(
    `INSERT INTO department_employee (department_id, employee_id, employee_number) VALUES ?`,
    [employees_array],
    (err, res) => {
      if (err) {
        console.log("error: ", err);
        result(err, null);
        return;
      }

      console.log("success: ", res);
      result(null, res);
    }
  );
};

当我使用上面的代码时,我得到

INSERT INTO department_employee (department_id, employee_id, employee_number) VALUES '[object Object]', '[object Object]'

这是不起作用的,原因很明显。我试着字符串化对象,我也试着使用for循环迭代Employees数组,但它不起作用,因为它说标头已经发送了。
我如何将数组(长度可能不同)存储到数据库中?先谢谢

pzfprimi

pzfprimi1#

按照mysql-转义查询值
嵌套数组转换为分组列表(用于大容量插入),例如[['a','b'],['c','d']]转换为('a','b'),('c','d')
您可能希望将值Map到数组,但不能将JSON对象的数组传递给查询

db.query(
    `INSERT INTO department_employee (department_id, employee_id, employee_number) VALUES ?`,
    [employees_array.map(employee => [employee.department_id, employee.employee_id, employee.employee_number])],
    (err, res) => {
      if (err) {
        console.log("error: ", err);
        result(err, null);
        return;
      }

      console.log("success: ", res);
      result(null, res);
    }
  );
};
xtfmy6hx

xtfmy6hx2#

如果你把你的数据做成一个数组的数组,那么我建议的解决方案将是安全的;

const employeesData = [
     [
      '6256f8ae6f749617e8167416',
      '6253ca0c6f749618a8d022af',
      '1234'
    ],
    [
     '6256f8ae6f749617e8167416',
     '6253ca0c6f749618a8d022af',
     '1503'
    ],
  ];

接下来,像这样准备查询;

const sql = `INSERT INTO images (department_id, employee_id, employee_number) VALUES?`;

现在您可以像下面这样运行查询了;

db
  .query(sql, [employeesData])
  .then(rows => {
     res.status(200).json({
       status: "success",
       message:"Data inserted successfully"
     });
   })
   .catch(err => {
     res.status(500).json({
       status: "error",
       error: err.message
     });
  });

您可以使用array的map方法生成要插入的值数组,如下所示:

employeesData = dataSourceArray.map ( (data) => {
  return [
     department_id,
     employee_id,
     employee_number
];
});
bgtovc5b

bgtovc5b3#

不能在表中插入数组,数组就是表

相关问题