Reputation: 425
Is there a Bulk insert for cordovaSQLite? I have a lot of Data, which I want to save in a sqlite Db.
My code now is
var query = "INSERT INTO Card (CardId, CardSetId, FrontText, BackText, ControlType, CardLevel, IsDirty, ChangedAt, Active) VALUES (?,?,?,?,?,?,?,?,?)";
for (var i = 0; i < cardList.length; i++) {
$cordovaSQLite.execute(db, query, [cardList[i].CardId, cardList[i].CardSetId, cardList[i].FrontText, cardList[i].BackText, cardList[i].ControlType, cardList[i].CardLevel, cardList[i].IsDirty, cardList[i].ChangedAt, cardList[i].Active]);
}
It works but is very very slow!
When I use this code :
var query = "INSERT INTO Card (CardId, CardSetId, FrontText, BackText, ControlType, CardLevel, IsDirty, ChangedAt, Active) VALUES ";
var data = [];
var rowArgs = [];
cardList.forEach(function (card) {
rowArgs.push("(?,?,?,?,?,?,?,?,?)");
data.push(card.CardId);
data.push(card.CardSetId);
console.log(card.CardSetId);
data.push(card.FrontText);
data.push(card.BackText);
data.push(card.ControlType);
data.push(card.CardLevel);
data.push(card.IsDirty);
data.push(card.ChangedAt);
data.push(card.Active);
});
query += rowArgs.join(", ");
$cordovaSQLite.execute(db, query, [data]).then(function (res) {
console.log("inserted");
}, function(err) {
console.dir(err);
});
Then I get the following error: sqlite3_step failure: NOT NULL constraint failed: Card.CardSetId
But in the data array CardSetId is not empty!
Is there a way to make it faster, or do it with a bulk insert?
Thanks
Upvotes: 0
Views: 2983
Reputation: 30356
You can try using cordova-sqlite-porter. Pass it your inserts as a JSON structure using importJsonToDb() and it will optimise the insertion into the SQLite DB.
The example project illustrates insertion of 15,000+ records. On a Samsung Galaxy S4, performing this using single SQL insert statements takes around 5 minutes/300 seconds, but the optimised JSON equivalent (using UNION SELECT - see here for info) takes around 3 seconds on the same device - 100X faster.
Upvotes: 4