I am trying to insert multiple rows in SQLite using ionic framework. Single row insert in working fine.
even if i run
INSERT INTO categories (category_id, category_name,category_type) VALUES (1,"test",1),(2,"test again", 2);
this is also working fine. but when i try to create a dynamic string it gives me error "could not prepare statement (1 near "?": syntax error)".
.success((function (result) {
var query = "INSERT INTO categories (category_id, category_name,category_type) VALUES ?";
var data = [];
result.forEach(function (category) {
data.push([category.id, category.category_name, category.category_type]);
});
$cordovaSQLite.execute(db, query,[data]).then(function (res) {
console.log("inserted");
}, function (err) {
console.dir(err);
});
It is not possible to use arrays as parameter values.
You have to create an SQL command string with three parameters for the three columns, and execute it multiple times.
To ensure efficiency, you have to do all INSERTs in a single transaction.
@Googie
Thanks for the solution. But I had problems with inserting the data and it came out that this line:
$cordovaSQLite.execute(db, query,[data])...
was the problem. And the solution was to write the data without brackets like this:
$cordovaSQLite.execute(db, query, data)...
because
data
is already an array.Thought this maybe could be helpful for others.
cheers
In any case it's a bad practice to write a raw sql queries in the code. Is it possible to use some Node ORM with ionic-framework? For example node-orm2: https://github.com/dresende/node-orm2
In this case your solution will looks like this:
Add multiple parameters to your insert, just like you do in your test query (the first you mentioned), then pass all arguments as a one dimensional array:
This code will produce query like:
and your data array will be of size 12, where every 3 entries in array will be one row of data to be inserted.
Those numbers are just example and they depend on the size of
result
.This seems to be an approach:
...
I have also seen this approach:
Ionic 2, angular 2 and typescript