将数组(对象数组)插入到MySQL数据库中

3

我只是在两个for循环中执行插入操作,就实现了我想要的结果,但我感觉最好还是等循环结束后再执行一次插入操作。

我尝试过:

1:插入对象数组 -> 只会插入数组中的第一个对象

  let itemsToDb = [];
  for (let i = 0; i < stashes.length; i++) {
    for (let j = 0; j < stashes[i].items.length; j++) {
      let item = stashes[i].items[j];
      let itemToDb = {
        item_id: item.id,
        verified: item.verified,
        icon: item.icon,
        name: item.name,
        typeline: item.typeLine,
        identified: item.identified,
        ilvl: item.ilvl,
        note: item.note,
        frametype: item.frameType,
        inventory_id: item.inventoryId,
        corrupted: item.corrupted,
        date: new Date().toJSON().slice(0, 19).replace('T', ' ')
      };
      itemsToDb.push(itemToDb);
    }
  }
  let sql = 'INSERT INTO items SET ?';
  db.query(sql, itemsToDb, (error) => {
    if (error) console.log(error);
    console.log(itemsToDb); //item added!
  });

2:插入数组的数组 -> 错误(请参见下文)

  let itemToDb = [
    item.id,
    item.verified,
    item.icon,
    item.name,
    item.typeLine,
    item.identified,
    item.ilvl,
    item.note,
    item.frameType,
    item.inventoryId,
    item.corrupted,
    new Date().toJSON().slice(0, 19).replace('T', ' ')
  ];

ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''45580327d5e9aa29bac9f4461029acd59c379006cdd622a6290ce28bff3496ee', false, 'http' at line 1

数据库结构如下:

这里输入图片描述

在INSERT中使用的item.id的值是什么?id是PRIMARY_KEY,如果您设置了自动增量,则可能会出现重复问题。如果您有真正的id,则必须使用REPLACE或使用INSERT将item.id的值设置为NULL。 - Pavel Musil
item_id(填充为item.id)是我从API数据获取的一些唯一哈希值。我不需要将id(即主键)添加到数组/对象中,对吧?它会自动计数,我想。 - Awesom-o
是的,没错 - 我现在看到了。我弄错名字了... - Pavel Musil
1个回答

2

在parse_error消息中,您可能会发现值没有列名。我不太了解节点的mysql模块中的对象参数。从读取sql错误消息来看,您尝试使用VALUES而不是SET进行插入:

INSERT INTO items (`item_id`, `verified`, `icon`, `name`, `typeline`, `identified`, `ilvl`, `note`, `frametype`, `inventory_id`, `corrupted`, `date`) VALUES ?

你让我走上了正确的轨道。所以确实使用VALUES,然后是[itemsToDb],而不仅仅是itemsToDb。谢谢! - Awesom-o
1
@Awesom-o:当你定义 SQL 数据库列时,让列名更具体化,不要使用 SQL 关键字 - date。这个列有一些原因:date_created_atcreated_at 或其他什么... - Pavel Musil
有道理,好的,我会去做的!谢谢你的提示! - Awesom-o
我能用mysql2 Node包来做这个吗? - Nithur

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接