如何在 node.js 中使用 sqlite3 执行批量插入?

Joh*_*mer 5 javascript sqlite bulkinsert node.js sql-insert

我需要向 sqlite3 表插入 10 行,插入完成后,将新行的 10 个 id 传递给数组中的回调函数。

我的问题是我不知道如何让准备好的语句一次执行多个插入。我找到了这篇关于如何使用 mySQL 执行此操作的帖子。

mySQL 中的批量插入

但这不适用于 sqlite。我的代码如下:

params = [[1,2],[3,4],[5,6],[7,8]]

stmt = db.prepare("INSERT INTO test (num1, num2) VALUES (?)");
stmt.all([params], function(err, res) {
    if(err) {
        console.log(err);
        return;
    } else {
        createdIDs = []
        for (i in result) {
            createdIDs.push(result[i].id);
        }
        nextFunction(createdIDs);
    }
});
Run Code Online (Sandbox Code Playgroud)

这给出了以下错误:

Error: SQLITE_ERROR: 1 values for 2 columns
at Error (native)
Run Code Online (Sandbox Code Playgroud)

表的模式是这样的:

db.run('CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY AUTOINCREMENT, num1 INTEGER NOT NULL, num2 INTEGER NOT NULL)')
Run Code Online (Sandbox Code Playgroud)

编辑:使用 Alvaro 的解决方案,我现在收到此错误消息:

{ [Error: SQLITE_CONSTRAINT: NOT NULL constraint failed: test.num1] errno: 19, code: 'SQLITE_CONSTRAINT' }
Run Code Online (Sandbox Code Playgroud)

Alv*_*oao 4

您必须按照值出现的顺序枚举它们:

db.run("INSERT INTO test (num1, num2) VALUES (?1,?2)");
Run Code Online (Sandbox Code Playgroud)

这就是为什么只检测到一个变量而不是预期的两个变量。

参考这里

另一种方法可以做到这一点:

// create the table
db.run('CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY AUTOINCREMENT, num1 INTEGER NOT NULL, num2 INTEGER NOT NULL)')

var params = [[1,2],[3,4],[5,6],[7,8]];
db.serialize(function() {
    db.run("begin transaction");

    for (var i = 0; i < params.length; i++) {
        db.run("insert into data(num1, num2) values (?, ?)", params[i][0], params[i][1]);
    }

    db.run("commit");
});
Run Code Online (Sandbox Code Playgroud)

参考:https ://gist.github.com/NelsonMinar/2db6986d5b3cda8ad167