Prepopulated SQLite Databases in Ionic

Yes, I did for android, I’m not sure is working too for IOS, but here you are what I did.

  • In your project you have to define the platform with cordova
ionic platform add android
  • Copy and paste your database in the android folder that you find it in platforms/android/assets

  • Add the plugins “cordova-plugin-dbcopy” and “Cordova-SQLitePlugin” to your project using

cordova plugin add https://github.com/an-rahulpandey/cordova-plugin-dbcopy
cordova plugin add https://github.com/brodysoft/Cordova-SQLitePlugin.git
  • Go to http://ngcordova.com/build/, check the SQLITE plugin and download the ng-cordova.min.js, copy and paste in your project and add like a script file into your index.html file in the head above the cordova.js file

  • Do the following changes in your app.js file

// global variable where will define the database
var db = null;

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();
    }

        /* DATABASE INTEGRATION */	 

	if (window.sqlitePlugin) {

		// copy the database
		window.plugins.sqlDB.copy("name_of_the_database.db",

		function () {
			// copy success, if not yet been copied
			// set "db" as the database
			db = window.sqlitePlugin.openDatabase({name: "name_of_the_database.db"});
		}, function() {
			// copy error, if it has already been copied
			// set "db" as the database
			db = window.sqlitePlugin.openDatabase({name: "name_of_the_database.db"});
		});
	}
  });
})
  • Now you can use the database using the following for example
.controller('ExampleCtrl', function($scope) {
	
	$scope.order = function(){
                // db is your database defined before
		db.transaction(function(tx) {
                        // running a sql querie 
			tx.executeSql("SELECT name, lastname FROM your_table_name ORDER BY name ASC", [], function(tx, res) {
				var len = res.rows.length;
				for (var i = 0; i < len; i++) { // loop as many times as there are row results
					alert( res.rows.item(i).name +' '+ res.rows.item(i).lastname ); // showing the results
				}
			}, function(e) {
				alert("ERROR: " + e.message);
			});
		});
	};
	
})

This last step is just an example of how you can do to run your queries. Later you can edit or do whatever you want with the database.

Well, that is what I did, I hope this help.

Regards.

1 Like