Skip to main content

Open Existing SQLite File In PhoneGap for Android and iOS

Step 1 :  Just Open command prompt and  Create the App


Go to the directory where you maintain your source code, and run a command such as the following:

cordova create hello com.example.hello HelloWorld


Step 2 :  Add Platform

All subsequent commands need to be run within the project's directory, or any subdirectories within its scope:
Before you can build the project, you need to specify a set of target platforms. Your ability to run these commands depends on whether your machine supports each SDK, and whether you have already installed each SDK.

cordova platform add android

{
(optional with working multi platforms)

Run this to check your current set of platforms:

cordova platforms ls

Run either of the following synonymous commands to remove a platform:

cordova platform rm android

}

Step 3 : Just Open command prompt and go to your project path and install plugin using CLI

cordova plugin add https://github.com/brodysoft/Cordova-SQLitePlugin.git
NOTE : Using CLI its very easy to install because we do not need to install any file manually all file will be placed automatically on folder.

Step 4 : Open Existing Database


For Android & iOS (only): put the database file in the www directory and open the database like:


var db = window.sqlitePlugin.openDatabase({name: "my.db", createFromLocation: 1});



// Wait for Cordova to load
document.addEventListener("deviceready", onDeviceReady, false);
var db;
function onDeviceReady() {
//Please place your db file in wwww directory ,here example : projectpath/www/santosh.db
   db = window.sqlitePlugin.openDatabase({name: "santosh.db", createFromLocation: 1});
}

IMPORTANT NOTES:
  • Put the pre-populated database file in the www subdirectory. This should work well with using the Cordova CLI to support both Android & iOS versions.
  • The pre-populated database file name must match exactly the file name given in openDatabase. The automatic extension has been completely eliminated.

Now here is the Example of Each SQL Transation

Insert Into Table

db.transaction(function(tx) {
tx.executeSql("INSERT INTO test_table (data, data_num) VALUES (?,?)", ["test", 100], function(tx, res) {
         console.log("insertId: " + res.insertId + " -- probably 1");
         console.log("rowsAffected: " + res.rowsAffected + " -- should be 1");
       });
});

Execute Other Queries

db.transaction(function(tx) {
tx.executeSql("select count(id) as cnt from test_table;", [], function(tx, res) {
 console.log("res.rows.length: " + res.rows.length + " -- should be 1");
 console.log("res.rows.item(0).cnt: " + res.rows.item(0).cnt + " -- should be 1");
});
});
this way you can use database in your app
NOTE : make sure db variable should be global accessible


Example :

index.html

<!DOCTYPE html>
<html>
   <head>
       <meta charset="utf-8" />
       <meta name="format-detection" content="telephone=no" />
       <meta name="msapplication-tap-highlight" content="no" />
       <!-- WARNING: for iOS 7, remove the width=device-width and height=device-height attributes. See https://issues.apache.org/jira/browse/CB-4323 -->
       <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
       <link rel="stylesheet" type="text/css" href="css/index.css" />
       <title>Hello World</title>
   </head>
   <body>
       <div class="app">
           <h1>Apache Cordova</h1>
           <div id="deviceready" class="blink">
               <p class="event listening">Connecting to Device</p>
               <p class="event received">Device is Ready</p>
           </div>
       </div>
       <script type="text/javascript" src="cordova.js"></script>
       <script type="text/javascript" src="js/index.js"></script>
   </body>
</html>

index.js

// Wait for Cordova to load
document.addEventListener("deviceready", onDeviceReady, false);

// Cordova is ready
function onDeviceReady() {
//For Android & iOS (only): put the database file in the www directory and open the database like:
var db = window.sqlitePlugin.openDatabase({name: "santosh.db", createFromLocation: 1});
 alert("conncting");
 db.transaction(function(tx) {
  // tx.executeSql('DROP TABLE IF EXISTS test_table');
 //  tx.executeSql('CREATE TABLE IF NOT EXISTS test_table (id integer primary key, data text, data_num integer)');

   tx.executeSql("INSERT INTO test_table (data, data_num) VALUES (?,?)", ["test", 100], function(tx, res) {
     alert("inserting");
     db.transaction(function(tx) {
       tx.executeSql("select count(id) as cnt from test_table;", [], function(tx, res) {
         alert("record"+res.rows.item(0).cnt);       
        });
     });

   }, function(e) {
     alert(e.message);
   });
 });

}

Comments

  1. thank You sir ....
    This article really helped me .... and saved lots of time for me....

    ReplyDelete
  2. welcome saurabh and thanks for your interest ..:)

    ReplyDelete
  3. This article really helped me ...thanks

    ReplyDelete
  4. Thanks Santosh!!!! Your post saved me...

    ReplyDelete
  5. Please place your db file in wwww directory ,here example : projectpath/www/santosh.db

    Hi tq for ur tutorial but I cant get where to put my db can u explain me ??? I have Projet path -> Hooks, Platforms, Plugins, WWW, config.xml

    I tried that saving in www inside folder. Not working

    ReplyDelete
  6. I have copied the .db file in main /projectPath/www directory, after building the platforms the file is copied for example into |platforms/android/assets/www" but when open database from javascript and make simple "SELECT" query it tells me that there is no such table... it seems like my db is not opened but is created a new one...

    I open the database like this: db = window.sqlitePlugin.openDatabase({name: "test.db", createFromLocation: 1});

    ReplyDelete
    Replies
    1. Please make sure selected tables are in file or not...

      Delete
    2. I also faced that error ..... The db file is created using sqlitebrowser v 3.8.0 plz reply me... Thank u

      Delete
  7. Hi, I'm testing with my local database, but I getting this error: "Cannot read property 'openDatabase' of undefined".
    Is it possible to test it in a web browser?

    ReplyDelete

Post a Comment

Popular posts from this blog

What exactly means MVW design pattern ?

What is a MVW framework? The abbreviation stands for 'Model - View - Whatever'.  Well there are many different JavaScript frameworks available , all invented for the same purpose. They all try to separate the presentation logic from the business logic where JavaScript holds the model and logic, and html the presentation layer. Quick overview : You can change the model without changing the view and vice-versa Unit testing is easy These are the core benefits of using such a framework. By separating presentation and business logic changes to the code are easier to implement and take less time. Another benefit is that code can be reused from a controller thus saving more time. Angularjs makes the code also shorter in comparison to other frameworks, which improves code stability. Less code means minor potential for bugs. For several years +AngularJS was closer to MVC (or rather one of its client-side variants), but over time and thanks to many refactorings...

File Upload & Download With ng-cordova File Transfer Plugin In Ionic Framework

Using the AngularJS extension set , ngCordova , with Ionic Framework and the Apache Cordova File Transfer plugin, you can easily upload files to a remote server and download files from a remote server. 1.Create the project ionic start Test blank cd Test ionic platform add android 2.Add Plugin org.apache.cordova.file-transfer https://github.com/apache/cordova-plugin-file-transfer This plugin allows you to upload and download files. This plugin defines global FileTransfer, FileUploadOptions Constructors. Although in the global scope, they are not available until after the deviceready event . Installation cordova plugin add cordova plugin add cordova-plugin-file-transfer     2.    org.apache.cordova.file             https://github.com/apache/cordova-plugin-file             This plugin implements a Fi...

Steps To Create Cordova Plugin

Introduction A plugin is a package of injected code that allows the Cordova webview within which the app renders to communicate with the native platform on which it runs. Plugins comprise a single JavaScript interface along with corresponding native code libraries for each supported platform. Due to following reason, we will go for plugin development To get the native capabilities of the device in the cordova based app Build the common functionality across the number of Cordova application(Reusability) Prerequisites For the creation of plugin you need to install plugman . npm install -g plugman Plugin Structure Decide Plugin ID & Name The plugin ID should be unique Plugin name should follow the convention “cordova.plugin.[your.plugin.name]” Create the structure Use the following command to create the plugin with plugin ID “cordova.plugin.test” and name “Test”. plugman create --name Test --...