Eivind
Eivind

Reputation: 301

node.js sqlite3 - error when adding rows dynamically

This error occurs when I add 20 strings to my table through a for-loop:

ERROR: SQLITE_ERROR: cannot start a transaction within a transaction at Error (native)

Here is the relevant code:

var sqlite3 = require('sqlite3').verbose();
var Players_db = new sqlite3.Database('./db/Players');

Players_db.serialize(function() 
{
    Players_db.run("BEGIN TRANSACTION");
    Players_db.run("CREATE TABLE IF NOT EXISTS Players(string TEXT)");
    Players_db.run("COMMIT");
    console.log('Players_db init')
});

// This part is a simplification, but it shouldn't make a difference.
for (var i = 0; i < 20; i ++) 
{
    Players_db.run("BEGIN TRANSACTION");
    Players_db.run("INSERT INTO Players VALUES('"+a_string+"')");
    Players_db.run("COMMIT");
}

It also appears that the for-loop finishes successfully (and data is being appended to the db), but shortly afterwards it crashes with the said error.

Upvotes: 0

Views: 601

Answers (1)

KlwntSingh
KlwntSingh

Reputation: 1092

Try this

        Players_db.serialize(function() 
        {
            Players_db.run("BEGIN TRANSACTION");
            for (var i = 0; i < 20; i ++) 
            {
               Players_db.run("INSERT INTO Players VALUES('"+a_string+"')");
            }
            Players_db.run("COMMIT");
        })

Upvotes: 1

Related Questions