Tuesday, 4 September 2012

Database problem in phonegap

In phone gap many times you can see that database operations are not working properly. In many cases I found that we are redirecting to some other page just after the database operation. Here is block of code,

insertData(data1, data2);
window.location = "abc.html";

And here is insertData function,


function insertDatas(data1, data2) {
        //Here I am assuming db is initialized properly.
db.transaction(insertHere, errorDataTable, successDataTable);
    function insertHere(tx) {
        var query = "insert into dataTable values('" + data1 + "','" + data2 + "')";
        tx.executeSql(query);
    }
    function errorDataTable(err){
          alert("Error : " + err);
    }
    function successDataTable() {
          alert("Success");
    }
}

Now here sometimes it may happen that, values are going to database. At place you may have update query In case of update values may not updated in database.

In order to fix this problem safe way to code in phonegap is to commit database after your operations. Here is code block with commit statement which is doing the same functionality as above but safely,

insertData(data1, data2);
//After this statement instead of redirecting call commit,

db.transaction(commit, errorCommit, successCommit);
 function commit(tx){
        tx.executeSql("COMMIT",[], commited, errorCommit);
 }
         
 function commited() {
        console.log('commit successful..');
        window.location = "abc.html";
}
         
function errorCommit() {
}
function successCommit() {
         console.log('commit successful.. redirecting');
        window.location = "abc.html"
}

So in phonegap always it is safe to commit your database. I have faced this problem with update statement.

No comments:

Post a Comment