0

In my HTML5, i have a for loop which calls a function to insert into a database. I need this function to be inside a single transaction.

function Ins(id){
db.transaction(function(tx){
tx.executeSql('insert into Product(id) values(?);', [iName], function() {}, function() { });
}); 
}

The for loop

    db.transaction(function(tx){tx.executeSql("BEGIN",[]);});
    for (intCountLine=1;intCountLine<=1000;intCountLine++)
    {
    Ins(intCount);
    }
   db.transaction(function(tx){tx.executeSql("COMMIT",[]);});

You can see, i have the transaction begin & commit, but i assume when it calls the INS function, it would open a new transaction and close it, everytime it is called. How do i make sure that doesn't happen.

googled it but could not find it... throw me some light here....

1 Answer 1

1

May be this will works. Use insert select union all instead of creating 1000 insert statements. But this can insert only 500 rows at a time. Here is the code which i worked on, do a test on Google chrome i am sure it works.

<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);
var msg;
var j=1;
var i=1;
var quer="";
db.transaction(function(tx){tx.executeSql("CREATE TABLE IF NOT EXISTS LOGS (ID INTEGER PRIMARY KEY ASC, todo TEXT)",[]);});
db.transaction(function(tx){tx.executeSql("delete from logs",[]);});
txquer();
showMsg();
function txquer()
{
  quer="insert into logs ";
 for(i=j;i<=j+498;i++)
 {
  quer+=" select "+i+",'test' union all";
  }
  quer+=" select "+i+",'test' ; ";
  j=i+1;
    db.transaction(
    function(tx){
      tx.executeSql(quer,[]);    
    }
    );

}

function showMsg(){
db.transaction(function (tx) {
  tx.executeSql('SELECT count(*) todo FROM LOGS', [], function (tx, results) {
   var len = results.rows.item(0).todo;
   msg = "<p>Found rows: " + len + "</p>";
   document.querySelector('#status').innerHTML +=  msg;  
 }, null);
});

}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.