How to insert multiple rows with a parameter? How to insert multiple rows with a parameter? sqlite sqlite

How to insert multiple rows with a parameter?


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:

.success((function (result) {                 var query = "INSERT INTO categories (category_id, category_name,category_type) VALUES ";                 var data = [];                 var rowArgs = [];                 result.forEach(function (category) {                         rowArgs.push("(?, ?, ?)");                         data.push(category.id);                         data.push(category.category_name);                         data.push(category.category_type);                     });                 query += rowArgs.join(", ");    $cordovaSQLite.execute(db, query,[data]).then(function (res) {         console.log("inserted");     }, function (err) {   console.dir(err);    });

This code will produce query like:

INSERT INTO categories (category_id, category_name,category_type) VALUES (?, ?, ?), (?, ?, ?), (?, ?, ?), (?, ?, ?);

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:

var query = "INSERT INTO categories (category_id,category_name,category_type) VALUES (?,?,?)";

...

.success((function (result) {$cordovaSQLite.transaction(function(tx){   result.forEach(function (category) {      tx.executeSql(query, [category.id, category.category_name, category.category_type]);   });}).success(function(){  .....});

I have also seen this approach:

$cordovaSQLite.execute("BEGIN IMMEDIATE TRANSACTION");result.forEach(function (category) {    $cordovaSQLite.executeSql(query, [category.id, category.category_name, category.category_type]);       });$cordovaSQLite.execute("COMMIT TRANSACTION");


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.