Creating database in Phonegap

24 / Sep / 2012 by Uday Pratap Singh 1 comments

Currently I am building a mobile app using Phonegap. In my project I need to store the data into the database and refresh it with server time to time.

Phonegap have the Storage API to do this. Storage API is based on the W3C HTML5 webdatabase. So we just need to create the database and corresponding table according to the webdatabase specification e.g;

var db = openDatabase("myApp", 1.0, "App database",200000)

Now to create tables and insert data into it using this db instance

    transaction.executeSql("CREATE TABLE user (username Integer default NULL, UNIQUE(username));");
    transaction.executeSql("INSERT INTO user (username) values ('uday');")

Now to get the data from this table we will simply write the select query. The executeSql method has its own success and failure callback method. Success callback gives the result set from the query e.g;

    transaction.executeSql("SELECT * from user where username=?",['uday'],successCallback,function(e){
       console.debug("some error") 

function successCallback(transaction,results){
    for (var i = 0; i < results.rows.length; i++) {
        var username = results.rows.item(i).username; 
       // Some code

The executeSql method takes four argument, first is the query, second array of values, if needed in the query, third success callback, which returns the result of query and last one error callback.


comments (1 “Creating database in Phonegap”)

  1. Abdul

    Can u please provide a sample for accessing prepopulated database using phonegap ??

    I have tried other tutorials but no result..

    Thanks in Advance..


Leave a comment -