使用forEach插入的排序不正确



我有一个包含对象的数组。我想把这些导入到sqlite3数据库中。我使用forEach循环完成此操作。效果很好。但我想知道为什么这些物体不是按我放入数据库的顺序导入。

这就是我所做的

const comments = [
{post_id: 1, comment: "lorem ipsum comment 1", comment_author: "user 1"},
{post_id: 2, comment: "lorem ipsum comment 2", comment_author: "user 1"},
]
comments.forEach(c => {
sql = `INSERT INTO comments(post_id, comment, comment_author) VALUES (?,?,?)`
db.run(sql, [c.post_id, c.comment, c.comment_author], (err) => {
if (err) { console.log(err.message)};
});
});

如果我现在执行一个select,我得到以下纯顺序(看一下post_id):

[
{id: 1, post_id: 2, comment: "lorem ipsum comment 2", comment_author: "user 1"},
{id: 2, post_id: 1, comment: "lorem ipsum comment 1", comment_author: "user 1"}
]

为什么会发生这种情况?我能做些什么来改变这种行为呢?

预期结果:

[
{id: 1, post_id: 1, comment: "lorem ipsum comment 1", comment_author: "user 1"},
{id: 2, post_id: 2, comment: "lorem ipsum comment 2", comment_author: "user 1"}
]

注意我猜这与javascript的异步有关。

你猜对了:I Guess it has something to do with the async of javascript.!

let placeholders = comments.map((c) => '(?)').join(',');
let sql = 'INSERT INTO comments(post_id, comment, comment_author) VALUES ' + placeholders;
// output the INSERT statement
console.log(sql);
db.run(sql, [comments], (err, results, fields) => {
if (err) {
return console.error(err.message);
}
// get inserted rows
console.log('Row inserted:' + results.affectedRows);
});
// close the database connection
db.close();

相关内容

  • 没有找到相关文章

最新更新