Sqlite create table error


#1

Hi there!
I’m using ionic Sqlite native plugin. When trying to create table I’m getting this error in the console:
“Console MessagesError: {“rows”:{“length”:0},“rowsAffected”:0}” which I don’t understand cause I think my code is ok.

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { SQLite, SQLiteObject } from "@ionic-native/sqlite";


@Injectable()
export class DatabaseProvider {
  theConsole: string = "Console Messages";

  options: any = {
    name: 'db_name.db',
    location: 'default'
  }

  private db: SQLiteObject;
  private isOpen: boolean;

  constructor(public http: HttpClient,private sqlite: SQLite) {
    console.log('Hello DatabaseProvider Provider');
    this.connectToDb();

  }

  private connectToDb():void {

   
      this.sqlite = new SQLite();
      this.sqlite.create(this.options)
        .then((db: SQLiteObject) => {
          this.db = db;
          this.isOpen = true;
          console.log('Hello DatabaseProvider connected to db');
          this.createTables();
        })
        .catch(e => {
          this.theConsole += JSON.stringify(e);
          console.log(this.getConsoleMessages());
        });
   
  }

  private createTables():void{
    this.createTableContatti();
  }

  private createTableContatti(): void{
    var sql = 'create table IF NOT EXISTS contatti(id_contatto INTEGER PRIMARY KEY AUTOINCREMENT,nome TEXT, data_nascita TEXT)';
    this.db.executeSql(sql)
      .then(() => {
      this.theConsole += 'Executed SQL' + sql
      console.log(this.getConsoleMessages());
      })
      .catch(e => {
        this.theConsole += "Error: "  + JSON.stringify(e)
        console.log(this.getConsoleMessages());
      });
  }

Can someone help please?
Thanks in advance


#2

SOLUTION: executeSql needs 2 parameters, query and data. If there are no data to pass then you should use empty array []. This works for ionic 4, for other versions is maybe different. So the code should be:

private createTableContatti(): void{
    var sql = 'create table IF NOT EXISTS contatti(id_contatto INTEGER PRIMARY KEY AUTOINCREMENT,nome TEXT, data_nascita TEXT)';
    this.db.executeSql(sql,[])
      .then(() => {
      this.theConsole += 'Executed SQL' + sql
      console.log(this.getConsoleMessages());
      })
      .catch(e => {
        this.theConsole += "Error: "  + JSON.stringify(e)
        console.log(this.getConsoleMessages());
      });
  }