Accessing database

Hi everybody,

I’ve got a problem on accessing database on my ionic 2 sample application. I followed the Nic Raboy tutorial sqlite storage tutorial to create SQLite storage,
and it seem’s doesn’t work for me when i try to insert data in my base.

My app.js code is ok, the database is well created in the initialize function, but my Test.js give me an error on the constructor parameter “platform: Platform” (see my constructor(platform: Platform) in Test.js).

Here’s my sample code

app.js

import {App, IonicApp, Platform, MenuController} from 'ionic-angular';
import {HelloIonicPage} from './pages/hello-ionic/hello-ionic';
import {TestPage} from './pages/test/test';

@App({
  templateUrl: 'build/app.html',
  config: {} // http://ionicframework.com/docs/v2/api/config/Config/
})
class MyApp {
  static get parameters() {
  return [[IonicApp], [Platform], [MenuController]];
}

constructor(app, platform, menu) {
// set up our app
this.app = app;
this.platform = platform;
this.menu = menu;
this.initializeApp();

// set our app's pages
this.pages = [
  { title: 'Hello Ionic', component: HelloIonicPage },
  { title: 'Test dabatase', component: TestPage},
];

// make HelloIonicPage the root (or first) page
this.rootPage = HelloIonicPage;
}

  initializeApp() {
this.platform.ready().then(() => {
  this.storage = new Storage(SqlStorage);
        this.storage.query('CREATE TABLE IF NOT EXISTS T_TASKS (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT)').then((data) => {
            console.log("TABLE CREATED -> " + JSON.stringify(data.res));
        }, (error) => {
            console.log("ERROR -> " + JSON.stringify(error.err));
  });
  if (window.StatusBar) {
    //window.StatusBar.styleDefault();
    window.Statusbar.styleHex('#A81910');
  }
});
}

openPage(page) {
    // close the menu when clicking a link from the menu
    this.menu.close();
    // navigate to the new page if it is not the current page
    let nav = this.app.getComponent('nav');
    nav.setRoot(page.component);
    }
}

My Test.js

import {Page, Platform, Storage, SqlStorage} from 'ionic-angular';
@Page({
    templateUrl: 'build/pages/test/test.html'
})

export class TestPage {
    static get parameters() {
        return [[IonicApp], [Platform]];
    }
  
 /************************************
  * Here's the error on the parameter platform: Platform
  ***********************************/
  constructor(platform: Platform) {

          this.platform = platform;
          this.cards = [];
          this.platform.ready().then(() => {
              this.storage = new Storage(SqlStorage);
              this.refresh();
          })
      }

  add() {

      if(this.title !== ""){
          this.platform.ready().then(() => {
              this.storage.query("INSERT INTO T_TASKS (title) VALUES (?)",this.title).then((data) => {
                  console.log(JSON.stringify(data.res));
                  alert("tache ajoutée " + this.title);
              }, (error) => {
                  console.log("ERROR -> " + JSON.stringify(error.err));
                  alert("erreur lors de l'ajout " + JSON.stringify(error.err));
              });
          });

          refresh();
      }
  }

  refresh() {
      alert("refresh");
      this.platform.ready().then(() => {
          this.storage.query("SELECT * FROM T_TASKS").then((data) => {
              this.cards = [];
              if(data.res.rows.length > 0) {
                  for(var i = 0; i < data.res.rows.length; i++) {
                      this.cards.push({title: data.res.rows.item(i).title});
                  }
              }
          }, (error) => {
              console.log("ERROR -> " + JSON.stringify(error.err));
          });
      });
  }
}

If i put empty parameter into constructor, i’ve no error but i can’t initialize my platform parameter. I also tried to set constructor(platform) but the error is still there.

If someone can give me a code review…thanks :wink:

From what I understand (I 'm still learning Ionic 2), your constructor should reflect the above parameters :
return [[IonicApp], [Platform]];
matches
constructor(app, platform)
without types

Damn ! that’s right, i forgot !

It is better but now, when i try to add a new element (in my add() method), i get the error case. but error.err gives no information.

For information, the database is well created and my refresh method is ok…

Those types are when you use the typescript version of Ionic 2, otherwise there’s no sense in using those types.

Sorry, i’m a beginner on ionic, so what do you mean by "Those types are when you use the typescript " ?

Is about this sample of code ?

static get parameters() {
    return [[IonicApp], [Platform]];
}

try to take a look at this http://ionicframework.com/docs/v2/api/platform/storage/SqlStorage/
much easy to use . look at your constructor at my Test.js platform: Platform its when you use typescript, someone added stars to show you the issue

Here’s my updated code (Test.js), constructor is now ok (no compilation error) but my add method thow the error case.

import {Page, Platform, Storage, SqlStorage} from 'ionic-angular';

@Page({
    templateUrl: 'build/pages/test/test.html'
})

export class TestPage {
    static get parameters() {
      return [[Platform]];
    }

constructor(platform) {
        this.platform = platform;
        this.cards = [];
        this.platform.ready().then(() => {
            this.storage = new Storage(SqlStorage);
            this.refresh();
        })
    }
  add() {

    if(this.title !== ""){
        this.platform.ready().then(() => {
            this.storage.query("INSERT INTO T_TASKS (title) VALUES (?)",this.title).then((data) => {
                console.log(JSON.stringify(data.res));
            }, (error) => {
                console.log("ERROR -> " + JSON.stringify(error.err));
            });
        });

        refresh();
    }
}

refresh() {
    this.platform.ready().then(() => {
        this.storage.query("SELECT * FROM T_TASKS").then((data) => {
            this.cards = [];
            if(data.res.rows.length > 0) {
                for(var i = 0; i < data.res.rows.length; i++) {
                   this.cards.push({title: data.res.rows.item(i).title});
                }
            }
        }, (error) => {
            console.log("ERROR -> " + JSON.stringify(error.err));
        });
    });
}
}

When using Typescript you can define the types of your variables and inputs to functions:

 constructor(platform: Platform) {
     // this is a type ^^^^^^^^  meant to be used in Typescript projects
 }

As you have the following in your code, you’re using the ES6 version of Ionic 2, it’s a common error since most docs, examples or tutorials out there reference the Typescript code:

static get parameters() {
        return [[IonicApp], [Platform]];
    }
1 Like

Ok i found my issue, it was my query syntax :

 `this.storage.query("INSERT INTO T_TASKS (title) VALUES (?)",this.title)`

Using (?,?) syntax seems to be uncorrect :confused: Some body can confirm it or i’m wrong with the syntax ?

Thanks

this.storage.query("INSERT INTO T_TASKS (title) VALUES (?)",[this.title])
1 Like

Thanks, you make my day :wink: