使用IONIC的SQLite请求

时间:2017-12-17 16:44:04

标签: sqlite ionic-framework

我正在尝试使用IONIC执行SQLite请求(INSERT和SELECT * FROM TABLE)。我寻求你的帮助......

1)我创建了一个数据库:

createDatabaseFile() {
    this.sqlite.create({
      name: DATABASE_FILENAME,
      location: 'default'
    })
      .then((db: SQLiteObject) => {
        this.db = db;
        //Create table 'favories':
        this.createTable("CREATE TABLE IF NOT EXISTS favories ( ID INTEGER PRIMARY KEY NOT NULL, cityNameFavory VARCHAR(100) );");
        console.log('DB well created.');
      })
      .catch(e => console.log(e));
  }

createTable方法如下:

 createTable(sqlInstruction) {
    this.db.executeSql(sqlInstruction, {})
    .then(
      () => {
      console.log('OK : ' + sqlInstruction);
    })
    .catch(e => console.log(e));
  }

2)我使用从.html调用的addFavorite(city)方法添加一个城市作为优惠:

    <ion-input [(ngModel)]="cityName" placeholder="Add a city..."></ion-input>
    <button ion-button icon-only (click)="addFavorite(cityName)">
      <ion-icon name="add"></ion-icon>
    </button>

我可以在console.log中获取cityName但是我没有成功将这个城市插入我的表中。 请在下面找到addFavorite方法:

addFavorite(city) {
    this.db.executeSql("INSERT INTO favories (cityNameFavory) VALUES(?);", {city})
    .then(() => {
      alert('Ville ajoutée !');
    })
    .catch(e => console.log(e));

  }

3)当我使用“SELECT x FROM”时,我无法检索我的数据,即使我很好地检索了行数:

getData() {
    this.db.executeSql("SELECT cityNameFavory FROM favories;", {})
    .then((data) => {
      if(data == null) {
        alert("Empty!")
            }

            if(data.rows) {
        console.log("Number of lines = " + data.rows.length);

                if(data.rows.length > 0) {
                    for(var i = 0; i < data.rows.length; i++) {
            this.listFavories.push(data.rows.item(i).cityNameFavory);
            alert(this.listFavories[i]);
          }

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

并且:

public listFavories: string[] = [];

请在下面找到我的详细信息:

cli包:

@ionic/cli-utils  : 1.19.0
ionic (Ionic CLI) : 3.19.0

全球套餐:

cordova (Cordova CLI) : 7.1.0

本地套餐:

@ionic/app-scripts : 3.1.4
Cordova Platforms  : none
Ionic Framework    : ionic-angular 3.9.2

系统:

Android SDK Tools : 26.1.1
Node              : v7.9.0
npm               : 4.2.0
OS                : Windows 10

1 个答案:

答案 0 :(得分:-1)

Finally, I modified my code as below:

this.db.executeSql('INSERT INTO `table` (cityName) VALUES(\'' + city + '\')', {})
    .then(() => {
      console.log("City added");
    })
    .catch(e => console.log(e));