【问题标题】:Using create for sqlite every time I have to execute a query每次我必须执行查询时使用 create for sqlite
【发布时间】:2018-05-10 02:06:03
【问题描述】:

我正在学习在 Ionic 中使用 SQLite。从我遵循的示例中,我想出了这段代码。

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { SQLite, SQLiteObject } from '@ionic-native/sqlite';

@IonicPage()
@Component({
  selector: 'page-sqlite',
  templateUrl: 'sqlite.html',
})
export class SqlitePage {

  constructor(public navCtrl: NavController, public navParams: NavParams, public sqlite: SQLite) {
    this.sqlite.create({
      name: 'data.db',
      location: 'default'
    })
    .then((db: SQLiteObject) => {
      db.executeSql('create table if not exists danceMoves(name VARCHAR(32))', {})
        .then(() => console.log('Executed SQL'))
        .catch(e => console.log(e));
    })
    .catch(e => console.log(e));
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad SqlitePage');
  }

  navigateToRegisterPage(){
    this.sqlite.create({
      name: 'data.db',
      location: 'default'
    })
    .then((db: SQLiteObject) => {
      db.executeSql('SELECT * FROM danceMoves', [])
        .then(res => {
          console.log(res);
          console.log('The SELECT has been succesfully executed');
        })
    })
  }

}

如果您查看 navigateToRegisterPage() 方法,我正在执行 SELECT,但我首先执行的是 this.sqlite.create。每次我想执行查询时都必须这样做,还是有其他方法可以做到这一点?

【问题讨论】:

    标签: sqlite typescript ionic-framework ionic3


    【解决方案1】:

    不,我认为您不需要每次都创建表,请参阅以下代码,它返回来自 SQLite 数据库的数据

    fetchdata(tablename, fields: Array<{}>): Promise<any> {
    
        let val: any = false;
        let field = "";
        for (var i = 0; i < fields.length; i++) {
            console.log("------- Value in the Fields Array is -------" + fields[i]);
            field += fields[i] + " " + 'TEXT,';
        }
        let query = "CREATE TABLE IF NOT EXISTS " + tablename + "(rowid INTEGER PRIMARY KEY,id INTEGER NOT NULL UNIQUE," + field + "col INT)";
    
        this.db.executeSql(query, {}).then(res => {
            console.log('Executed SQL')
        }).catch(e => console.log(e));
    
        this.db.executeSql("SELECT * FROM " + tablename, {}).then(res => {
            val = res;
        })
    
        return val;
    }
    

    【讨论】:

      猜你喜欢
      • 2017-04-24
      • 1970-01-01
      • 1970-01-01
      • 2017-03-29
      • 1970-01-01
      • 2016-11-04
      • 1970-01-01
      • 2020-02-04
      • 1970-01-01
      相关资源
      最近更新 更多