Storing data inside database with Ionic

Hello everyone,

I am currently trying to understand how to store the data of my app (e.g user data) with a database. I need this data to be persistent because its going to be used later on.

I have seen that there is this SQLite plugin (https://github.com/litehelpers/Cordova-sqlite-storage), however I think I don’t understand some basics about storing data in a database in Ionic v2.

I already started to write a little provider with functions that should create a database and a table for me. Where should I call this function for the first time? Is it meant to be inside the constructor of my provider like in this example?

constructor(public http: Http, private platform: Platform, private sqlite: SQLite) {
	this.platform.ready()
		.then( () => {
			this.createDB()
				.then( () => {
					this.initTables();
				})
		})
}

createDB(): Promise<any>{
	return new Promise( (resolve, reject) => {
		try {
			this.database.create({name: 'data.db', location: 'default'})
				.then( (db: SQLiteObject) => {
					this.database = db;
				})
		} catch (err) {
			reject( {err: err} );
		}
	})
}

initTables(){
	this.platform.ready().then( () => {
		this.database.transaction( (tx: any) => {
			tx.executeSql('CREATE TABLE IF NOT EXISTS User(id INT NOT NULL, name VARCHAR(40) NOT NULL)');
		})
			.then( () => { console.log('Created User table') })
			.catch(err => {
            	console.error('Unable to create initial storage tables', err.tx, err.err);
        	});
	});
}

Also what I would like to know is if this example code is in general the correct way of doing it? If it is not, could you maybe provide me a little example on how to do it properly?

Thanks in advance

If simple key/value storage is enough, use ionic storage.

2 Likes

This was just an example, I need to store more attributes than only id and name. Also I need to store other data that is not user related.
Is this still going to work with ionic storage? And will it be persistent?

Thanks

Yes, this will be possible.
Yes, this will be persistent.

It just won’t be relational like SQL, but a key-value store like NoSQL.

1 Like