Ionic2调用本地SQlite实例
普通的app用ionic内置的Storage存储键值对的方式可以满足日常的使用,但是有时候遇到一些奇怪的需求。比如说有个网友留言说做一个离线版的App,怎样调用本地Sqlite执行SQL语句。问题描述清楚直接上代码。
需要说明的是SQLite是手机内置的数据库存储方式,在Ionic2中需要安装相应的插件和安装包。过程很简单
第一步
安装插件、并加入项目
$ionicpluginaddcordova-sqlite-storage $npminstall--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' }) exportclassHelloIonicPage{ constructor( privatesqlite:SQLite){ } database:SQLiteObject; ngOnInit(){ this.initDB(); } initDB(){ this.sqlite.create({ name:'data.db', location:'default' }) .then((db:SQLiteObject)=>{ db.executeSql('createtablet_log(nameVARCHAR(32))',{})//建表 .then(()=>console.log('ExecutedSQL')) .catch(e=>console.log(e)); this.database=db; db.executeSql("insertintot_logvalues('123')",{});//插入数据 }) .catch(e=>console.log(e)); } //查询 query(){ letresults=this.database.executeSql("select*fromt_log",{}); alert(data.rows.length); alert(data.rows.item(0).name); }) } }
最后一步
这一步一定要生成app安装到手机才能得到结果,毕竟是调用手机内置的SQLite。
ionicbuildandroid
用上面的命令构建APP并安装到手机看看效果吧
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。