Database persistence


#1

hi all.

i was able to use sqlite for database persistence and everything Works fine until i refresh the browser or i restart the App in the mobile. It’s like the database is 'gone once the App ends.
what can i do to persist the database in a permanent way

to add more details, i am using the sqlite plugin for the mobile and even sample code have this behavior


#2

How are you calling your data base? In a controller of factory?


#3

in a factory:

app.factory('DB',function($q, DB_CONFIG) {
    var self = this;
    self.db = null;
    self.init = function() {
// Use self.db = window.sqlitePlugin.openDatabase({name: DB_CONFIG.name}); in production
        //self.db = window.sqlitePlugin.openDatabase(DB_CONFIG.name,"1.0",DB_CONFIG,-1);
        self.db = window.sqlitePlugin.openDatabase({name: DB_CONFIG.name});
            angular.forEach(DB_CONFIG.tables, function(table) {
                var columns = [];
                angular.forEach(table.columns, function(column) {
                    columns.push(column.name + ' ' + column.type);
                });
                var query = 'CREATE TABLE IF NOT EXISTS ' + table.name + ' (' + columns.join(',') + ')';
                self.query(query);
                console.log('Table ' + table.name + ' initialized');
            });
        };

i took the code from here:


#4

Hmm, DBs are not my strongest point, but you may want to check out the cordova sqlite plugin.


#5

thank you, problem solved now!!!


#6

@mhartington I got an error with the $cordovaSQLite:
Error: ‘undefined’ is not a function (evaluating ‘e.transaction(function(n){n.executeSql(o,r,function(n,e){q.resolve(e)},function(n,e){q.reject(e)})})’) at ionic.bundle.js:19272

here the code in my controller:

    $scope.dbTest = function(){
    var db = 'testing';
    var query = '';
    $cordovaSQLite.openDB(db);
    query = 'CREATE TABLE IF NOT EXISTS MyTable (id INTEGER PRIMARY KEY ASC, text_sample TEXT, date_sample DATE)';
    $cordovaSQLite.execute(db, query, [])
    .then(function(data){
                  console.log(data);
                  });
    query = 'INSERT INTO MyTable(text_sample, date_sample) VALUES ("Registro teste","2014-05-28")';
    $cordovaSQLite.execute(db, query, [])
    .then(function(data){
                  console.log(data);
                  });
    query = 'SELECT * FROM MyTable ORDER BY id';
    $cordovaSQLite.execute(db, query, [])
    .then(function(data){
                  console.log(data);
                  });
  }

I’m using the last launch: 1.0.0-beta.9 Gadolinium Gator (2014-07-02)
testing in iOS simulator and device… the DB is opened, but the $cordovaSQLite.execute(db, query, binding) function have no success… :confused: