Help with sqlite


#1

Hi,

I’m in trouble with ionic and sqlite.
I need to know whether to create a file called app.db so I can create the tables by ionic.
Where should I put this file to the ionic can read?

The error I’m getting is that the table does not exists.

Thanks.


#2

You can use something like to create table:

var db = window.openDatabase(“text”, “”, “xxx”, 2000000);
db.transaction(
function(tx) {
tx.executeSql(‘CREATE TABLE IF NOT EXISTS foo (id integer, bar text)’);
},
function(){console.log(‘error’);}
);

Or follow this example to prepopulate the db: http://www.raymondcamden.com/2012/07/27/Guest-Blog-Post-Shipping-a-populated-SQLite-DB-with-PhoneGap


#3

Thanks fabio.

I’m having another problem.
I’m using db variable inside a controller but the variable value is always null.
How can I access the db variable inside a controller ?

Thanks.


#4

…please post your code…


#5

Sorry.

This code works:

if(window.cordova) {
// App syntax
var db = $cordovaSQLite.openDB(“myapp.db”);
} else {
// Ionic serve syntax
var db = window.openDatabase(“myapp.db”, “1.0”, “My app”, -1);
}

$cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS teste (name text)");

In the controller:

var query = “SELECT * FROM teste”;

$cordovaSQLite.execute(db, query).then(function(res) {
if(res.rows.length > 0) {
$scope.teams = res.rows;
//console.log("SELECTED -> " + res.rows.item(0));
} else {
console.log(“No results found”);
}
}, function (err) {
console.error(err);
});

Occurrs an error at db reference.


#6

The db var must exist and be defined, so you can use into your controller:

var db = $cordovaSQLite.openDB({ name: "myapp.db" }); 

to (re)open the db, or save the db variable somewhere (scope?).


#7

See the best solution: https://github.com/jdnichollsc/Ionic-Starter-Template

Regards, Nicholls