我只是通过在2个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
在parse_error消息中,您可能会看到值没有列名。我不完全了解节点的mysql模块中的对象参数。通过阅读sql错误消息,您尝试使用未设置VALUES的INSERT:
INSERT INTO items (`item_id`, `verified`, `icon`, `name`, `typeline`, `identified`, `ilvl`, `note`, `frametype`, `inventory_id`, `corrupted`, `date`) VALUES ?