Search code examples
sqlitetypescriptcordovavisual-studio-codeionic4

Ionic: SQL Lite Insert Into Statement does not work


I'm trying to create a simple Android App with Ionic. I want to use a SQL Lite db with the help of some articles on SQL Lite and Ionic and Ionic and Cordova from browser. I managed to setup my db (at least my App seems to run) with the following code used in app.components.ts after this.initializeApp() :

init_db(){
var config = this.sqlite.create({
  name: 'data.db',
  location: 'default'
})
.then((db: SQLiteObject) =>{
  this.db = db;
  db.executeSql('CREATE TABLE "ExpenseModel" ( `EXPENSE_LIMIT` INTEGER NOT NULL, `ID` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, `MODEL_NAME` TEXT NOT NULL UNIQUE, `PINNED` INTEGER )');
  // .then(() => console.log('Executed'))
  // .catch(e=> console.log(e));

});
// .catch(e => console.log(e));

(exception handling is commented out only to see if an exception is thrown)

However, the following code doing a simple SQL Lite insert does not work:

this.db.executeSql('INSERT INTO "ExpenseModel" (EXPENSE_LIMIT, ID, MODEL_NAME, PINNED) VALUES ( 5,1, \'asd\', 1)');

When I run the app with ionic cordova run browser, I get a white screen. When I run it with ionic serve and catch all the exceptions (otherwise even db init will not work) I get the error Cannot read property 'executeSql' of undefined

What is it that I'm doing wrong? My insert code worked in an online editor, so I do not assume it's the SQL.


Solution

  • 1 -> Install the Cordova and Ionic Native plugins:
    ionic cordova plugin add cordova-sqlite-storage
    npm install --save @ionic-native/sqlite

    2 -> Add this plugin to your app's module
    import {SQLite} from "@ionic-native/sqlite";
    providers: [ SQLite, ]

    3 -> in AddItem Page import this:

     import {SQLite, SQLiteObject} from '@ionic-native/sqlite'; <br>
     constructor(private sqlite: SQLite);
     addItem() {
        this.sqlite.create({
            name: 'ionicdb.db',
            location: 'default'
        }).then((db: SQLiteObject) => {
            db.executeSql('INSERT INTO bikes VALUES(NULL,?,?,?,?,?)', [this.date, this.item.modal, this.item.company, this.item.color, this.imageString])
                .then((res) => {
                    this.presentToast("Data Saved Successfully");
                })
                .catch((err) => {
                    console.log('Error in SaveData------');
                    console.log(JSON.stringify(err));
                    this.presentToast("Error in SaveData");
                });
        }).catch((e) => {
            console.log("ERROR in SaveData:------");
            console.log(JSON.stringify(e));
            this.presentToast("ERROR in SaveData");
        });
        this.navCtrl.push(HomePage);
    }
    

    Then build your project and run in actual Device. ex: Android Phone.
    SQlite require Actual Device to perform Correctly..

    This Works for me like charm. hope this will help you... :)