Ionic using Sqlite

Sqlite is better than ‘local storage’ and ‘session’ for complex data relationship on ionic/cordova platform.

Here is instruction on how to install

1. create an empty ionic app
$ ionic start myApp blank –type ionic1

2. add Cordova for sqlite native plugin
$ bower install ngCordova
it will install ‘www/lib/ngCordova/’.

3. install sqlite native plugin
$ ionic cordova plugin add cordova-sqlite-storage
$ npm install –save @ionic-native/sqlite

4. in www/index.html, add

5. in app.js make app.js looks like.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
var myApp = angular.module('starter', ['ionic','ngCordova'])
 
    .run(function($ionicPlatform, $cordovaSQLite) {
 
        $ionicPlatform.ready(function() {
            if(window.cordova && window.cordova.plugins.Keyboard) {
                // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
                // for form inputs)
                cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
 
                // Don't remove this line unless you know what you are doing. It stops the viewport
                // from snapping when text inputs are focused. Ionic handles this internally for
                // a much nicer keyboard experience.
                cordova.plugins.Keyboard.disableScroll(true);
 
            }
            if(window.StatusBar) {
                StatusBar.styleDefault();
            }
 
            var db;
            if (window.cordova) {
                db = $cordovaSQLite.openDB({ name: "my.db" }); //device
            }else{
                db = window.openDatabase("my.db", '1', 'my', 1024 * 1024 * 100); // browser
            }
            $cordovaSQLite.execute(db,"create table if not exists people(id integer primary key, firstname text, lastname text)");
            //$cordovaSQLite.deleteDB("my.db");  
 
        });
    })

Key Important code:

1
2
3
4
5
            if (window.cordova) {
                db = $cordovaSQLite.openDB({ name: "my.db" }); //device
            }else{
                db = window.openDatabase("my.db", '1', 'my', 1024 * 1024 * 100); // browser
            }

this code snippet is key important because when running on browers using ‘ionic serve’, we use ‘window.openDatabase’ rather than native plugin.