Use SQLite Instead of Local Storage In Ionic Framework

by - May 31, 2016

Often, it can be a tough task, when you have to switch to object-based data storage. When you are switching over from native development to Phonegap or Ionic Framework development, it might get difficult to grasp the whole local storage concept. You might prefer a structured query language (SQL) when the data is to be worked upon.

Because there is a plugin for that, there is nothing to worry!

If you want to manage the data in Android or iOS, you can use a SQLite data source by using the
Cordova SQLite plugin by Chris Brody. When you pair this with ngCordova, you get a better
AngularJS experience complimenting your Ionic Framework development.




Refer this tutorial instead, whenever you are using Ionic2.

We can start making a new project, just as it is in all my tutorials.


ionic start IonicProject blank
cd IonicProject
ionic platform add android
ionic platform add ios



With the library file included, we now need to include it in our project. Open your index.html file and add the following highlighted line:
To add and build the iOS platform, you need to be on a Mac computer.

Next is , to add the SQLite plugin. The following command will help to do it.




Once we include the usage of ngCordova, it will be easier to work on an an Ionic Framework article.

Now that we have included he library file, open your index.html file and insert the highlighted line given below. This is to include the library file in our project.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
        <title></title>
        <link href="lib/ionic/css/ionic.css" rel="stylesheet">
        <link href="css/style.css" rel="stylesheet">
        <script src="lib/ionic/js/ionic.bundle.js"></script>
        <script src="js/ng-cordova.min.js"></script>
        <script src="cordova.js"></script>
        <script src="js/app.js"></script>
    </head>
    <body ng-app="starter">

Keeping this in mind,I’m going to open the database in the modules .run() method like so:

var db = null;

var example = angular.module('starter', ['ionic', 'ngCordova'])
    .run(function($ionicPlatform, $cordovaSQLite) {
        $ionicPlatform.ready(function() {
            if(window.cordova && window.cordova.plugins.Keyboard) {
                cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
            }
            if(window.StatusBar) {
                StatusBar.styleDefault();
            }
            db = $cordovaSQLite.openDB("my.db");
            $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS people (id integer primary key, firstname text, lastname text)");
        });
    });


Do take a note of the highlighted lines. Since the database is to be accessed globally, I create a
variable outside of any method or controller.

Now, we include $cordovaSQLite in the .run() method to use the ngCordova functions.

Finally, a new a new database called my.db and a fresh table called people created by mean be seen.

Hence, we are left with a usable database ready for activity in our controllers.

Consider the following example:


example.controller("ExampleController", function($scope, $cordovaSQLite) {

    $scope.insert = function(firstname, lastname) {
        var query = "INSERT INTO people (firstname, lastname) VALUES (?,?)";
        $cordovaSQLite.execute(db, query, [firstname, lastname]).then(function(res) {
            console.log("INSERT ID -> " + res.insertId);
        }, function (err) {
            console.error(err);
        });
    }

    $scope.select = function(lastname) {
        var query = "SELECT firstname, lastname FROM people WHERE lastname = ?";
        $cordovaSQLite.execute(db, query, [lastname]).then(function(res) {
            if(res.rows.length > 0) {
                console.log("SELECTED -> " + res.rows.item(0).firstname + " " + res.rows.item(0).lastname);
            } else {
                console.log("No results found");
            }
        }, function (err) {
            console.error(err);
        });
    }

});

Here, what we have done is created two basic functions:

1. The insert function: This will add first and last name record into the database.
2.  The select function: This will find records by last name.

Hopefully, he concept is c;ear to you.
Let me mention a few more points about my controller here. These database calls are nt being inside an onDeviceReady()function. Had these functions been fired when the controller loads,
they probably would have failed. The probability to assume that the the device and database is ready for use is since I am basing the database activity off button clicks. 

For deleting any of your any of your SQLite databases, include this:

$cordovaSQLite.deleteDB("my.db");


You can also make use of various other ngCordova and baseline SQLite commands.

The plugin documentation is very thorough and worth a read.














You May Also Like

0 comments