Ionic2 调用本地SQlite

普通的app用ionic内置的Storage存储键值对的方式可以满足日常的使用,但是有时候遇到一些奇怪的需求。比如说有个网友留言说做一个离线版的App,怎样调用本地Sqlite执行SQL语句。问题描述清楚直接上代码。
需要说明的是SQLite是手机内置的数据库存储方式,在Ionic2中需要安装相应的插件和安装包。过程很简单

  • 第一步

安装插件、并加入项目

$ ionic plugin add cordova-sqlite-storage
$ npm install --save @ionic-native/sqlite
  • 第二步

把服务加入到src/app/app.moudle.ts

...
import { SQLite } from '@ionic-native/sqlite';
...
providers: [
    ...
    SQLite
  ]
...
  • 第三步

使用数据库,常规来说,这一步应该封装成公共服务或者工具类。类中是具体的创建数据库,调用数据库,CRUD等方法。这里只是说明原理,直接调用

import { Component } from '@angular/core';
import { SQLite, SQLiteObject } from '@ionic-native/sqlite';
@Component({
  selector: 'page-hello-ionic',
  templateUrl: 'hello-ionic.html'
})
export class HelloIonicPage {
  constructor(
              private sqlite: SQLite) {

  }
 database :SQLiteObject;
  ngOnInit(){
    this.initDB();
  }
  initDB(){
    this.sqlite.create({
      name: 'data.db',
      location: 'default'
    })
    .then((db: SQLiteObject) => {
    db.executeSql('create table t_log(name VARCHAR(32))', {})//建表
      .then(() => console.log('Executed SQL'))
      .catch(e => console.log(e));

    this.database = db;
    db.executeSql("insert into t_log values('123')",{});//插入数据
    })
    .catch(e => console.log(e));

  }
//查询
query() {
    let results = this.database.executeSql("select * from t_log",{});
    alert(data.rows.length);
    alert(data.rows.item(0).name);
    })
 }
}

  • 最后一步

这一步一定要生成app安装到手机才能得到结果,毕竟是调用手机内置的SQLite。
ionic build android
用上面的命令构建APP并安装到手机看看效果吧

    原文作者:蓝山牧童
    原文地址: https://www.jianshu.com/p/ca2f87cd3280
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞