7

I have a JavaScript object with multiple rows of data and I want to insert it into web sql database. Here is how my code looks like.

for(i in rows)
{
    (function(row){
        db.transaction(function(tx) {
            tx.executeSql("INSERT INTO my_table (id, name, parent_id) VALUES (?, ?, ?)",
                [ row.id, row.name, row.parent_id ], onSuccess, onError
            );
        });
    })(rows[i]);
}

My questions about this are:

  1. This can be done by moving outer loop inside db.transaction. Will it be better and why?
  2. Is it possible to add multiple rows in single query like multiple values in single MySQL INSERT? Or I should not worry about this.
Musa
  • 96,336
  • 17
  • 118
  • 137
Naveed
  • 1,191
  • 10
  • 22
  • purely sql options: http://blog.sqlauthority.com/2012/08/29/sql-server-three-methods-to-insert-multiple-rows-into-single-table-sql-in-sixty-seconds-024-video/ – Stefan Nov 14 '12 at 19:50
  • http://stackoverflow.com/questions/452859/inserting-multiple-rows-in-a-single-sql-query – Stefan Nov 14 '12 at 19:51
  • possible duplicate of [Web SQL insert data into multiple rows](http://stackoverflow.com/questions/19477840/web-sql-insert-data-into-multiple-rows) – Chepech Apr 24 '14 at 22:16

1 Answers1

3

This can be done by moving outer loop inside db.transaction. Will it be better and why?

yes. much better. 1) creating a transaction is not cheap. 2) looping async is generally bad .

Is it possible to add multiple rows in single query like multiple values in single MySQL INSERT? Or I should not worry about this.

don't worry. Multiple rows workaround are syntactic sugar. No performance benefit. Better loop it under one transaction.

Again do not loop executeSql, it is async.

Kyaw Tun
  • 12,447
  • 10
  • 56
  • 83
  • I am facing problem in this that when i insert multiple rows in db.transaction function than it only inserting last row multiple times. I agree with you that due to async it is performing this king of behavior,can you please let me know what would be the solution and if you can give any sample than it will help me out in better way. – Saurabh Android Apr 02 '14 at 15:08