Mahesh
Mahesh

Reputation: 524

Working with Cordova Sqlite plugin in ionic 2

I'm new to ionic 2 development (haven't worked with ionic-1 either).

I'm trying to use cordova sqlite plugin in the application. I followed Use SQLite in Ionic 2 link. Was able to add the plugin into to project using following command.

$ ionic plugin add cordova-sqlite-storage

After deploying the app on real device data.db was created and opened and also the peopletable was created successfully. Following is the log from the Xcode :

2016-10-17 16:29:16.435992 SqlProject[238:3982] -[SQLitePlugin pluginInitialize] [Line 67] no cloud sync at path: /var/mobile/Containers/Data/Application/DFDADD59-D48E-4D4C-B8F0-23EEDE169471/Library/LocalDatabase 2016-10-17 16:29:16.436138 SqlProject[238:4034] -[SQLitePlugin openNow:] [Line 137] open full db path: /var/mobile/Containers/Data/Application/DFDADD59-D48E-4D4C-B8F0-23EEDE169471/Library/LocalDatabase/data.db 2016-10-17 16:29:16.443765 SqlProject[238:4034] -[SQLitePlugin openNow:] [Line 163] Good news: SQLite is thread safe! 2016-10-17 16:29:16.448487 SqlProject[238:3982] OPEN database: data.db - OK 2016-10-17 16:29:16.463667 SqlProject[238:3982] TABLE CREATED: [object Object]

Code for Opening Database:

import { SQLite } from 'ionic-native';

 constructor(platform: Platform) {
   platform.ready().then(() => {
   StatusBar.styleDefault();

   let database = new SQLite();
        database.openDatabase({
            name: "data.db",
            location: "default"
        }).then(() => {
            database.executeSql("CREATE TABLE IF NOT EXISTS people (id INTEGER PRIMARY KEY AUTOINCREMENT, firstname TEXT, lastname TEXT)", {}).then((data) => {
                console.log("TABLE CREATED: ", data);

            }, (error) => {
                console.error("Unable to create table", error);

            })
        }, (error) => {

            console.error("Unable to open database", error);
        });
   });
}

But, now I'm getting error while Inserting and Fetching the records from the db.

 public add() {

 console.log("Inside the add function- ");

 this.database.executeSql("INSERT INTO people (firstname, lastname) VALUES (?, ?)", ['mahesh', 'bhalerao']).then((data) => {

   console.log("INSERTED: " + JSON.stringify(data));

 }, (error) => {
   console.log("ERROR: " + JSON);
 });
}

 public fetchRecords() {

    this.database.executeSql("SELECT * FROM people", []).then((data) => {
               alert("executeSql refresh function success");

        this.people = [];

        if(data.rows.length > 0) {
            for(var i = 0; i < data.rows.length; i++) {
                this.people.push({firstname: data.rows.item(i).firstname, lastname: data.rows.item(i).lastname});
            }
        }
    }, (error) => {
        console.log("ERROR: " + JSON.stringify(error.err));
    });
}

I'm getting undefined error.

ERROR: undefined

Not sure what's going wrong.

Any help would be appreciated. Thanks!

Upvotes: 0

Views: 1763

Answers (1)

Fylax
Fylax

Reputation: 1128

First snippet, fifth line: you have let database = new SQLite();; you create the database onto the disk (if it doesn't exists yet) and then you quit from contructor.

Due to the scoping of let, once you exit from the costructor, the database variable doesn't exists, to the add and fetch methods it has never existed.

Instead of let you should put database into an attribute (that is where the methods are looking for it) and then everything should work fine.

In other words you should have a similar code:

public database: SQLite //here the attribute

constructor(platform: Platform) {
   platform.ready().then(() => {
   StatusBar.styleDefault();

   this.database = new SQLite(); //here you initialize the attribute instead of a volative variable
   this.database.openDatabase({ //in this block you open an then populate the attribute
            name: "data.db",
            location: "default"
        }).then(() => {
            database.executeSql("CREATE TABLE IF NOT EXISTS people (id INTEGER PRIMARY KEY AUTOINCREMENT, firstname TEXT, lastname TEXT)").then((data) => {
                console.log("TABLE CREATED: ", 
            }, (error) => {
                console.error("Unable to create table", error);
            });
        }, (error) => {
            console.error("Unable to open database", error);
        });
   });
}

Upvotes: 0

Related Questions