Reputation: 833
I'm trying out Ionic framework. I need to store some data in the Android SQLite. So, I want to open or create a database and if database didn't exist before, populate it with some data.
Here it says I use create
method even if the database already exists:
https://ionicframework.com/docs/native/sqlite/
So I wrote a class:
export class Database {
private sqlite: SQLite;
private database: SQLiteObject = null;
constructor() {
this.sqlite = new SQLite();
}
private open_db() {
return this.sqlite.create({
name: 'data.db',
location: 'default'
})
.then((db: SQLiteObject) => {
this.database = db;
return db.sqlBatch([...some sql inserts and create tables...]);
});
});
public all() {
return this.open_db().then(() => this.database.executeSql("SELECT ...something...", []));
}
Now, how do I call the db.sqlBatch only when database is actually created, not just opened? And yes, this code throws random exception without reasonable explanation that could be seen in logcat, any advice would be appreciated.
Upvotes: 2
Views: 8672
Reputation: 143
Use the openDatabase command instead of create. This will create the database if it doesn't exist.
Try following this article
https://www.thepolyglotdeveloper.com/2015/12/use-sqlite-in-ionic-2-instead-of-local-storage/
Also I would recommend use this command at the start of $ionicPlatform.ready and save it in some global variable this way you can access it any time in the application. I have been using sqlite plugin with ionic v1. Above link will help you integrating it with ionic v2.
Upvotes: 5