不管是真机还是H5,都有提供sqlite数据库进行存储数据。那么我们只要封装好函数就能随意调用了。
如果只是存储简单的键值对形式的话,ionic官网也提供了一个兼容网页的storage,https://ionicframework.com/docs/storage,但只能key/value ,当然value可以是Json。
但是很多时候为了前后端数据保存一致,所以前端也采用多字段存储,那么只能自己封装函数处理了。
1. 安装数据库操作插件
官网地址:https://ionicframework.com/docs/native/sqlite/
$ ionic cordova plugin add cordova-sqlite-storage
$ npm install --save @ionic-native/sqlite
所有的原生插件和自定义provider都要在app.module的providers中声明
import { SQLite } from '@ionic-native/sqlite';
@NgModule({
declarations: [
MyApp
],
imports: [
HttpModule,
JsonpModule,
BrowserModule,
IonicModule.forRoot(MyApp, {
})
],
bootstrap: [IonicApp],
entryComponents: [
MyApp
],
providers: [
SQLite
]
})
export class AppModule { }
2. 封装调用函数
控制台输入命令创建provider
$ ionic g provider native
执行后目录如下:
填入//异步问题进行修改
import { SQLite, SQLiteObject } from '@ionic-native/sqlite';
import { Injectable } from '@angular/core';
import { Platform , Events } from 'ionic-angular';
import { StorageServiceProvider } from '../../providers/storage-service/storage-service';
@Injectable()
export class NativeProvider {
database: SQLiteObject;
win_db: any;//H5数据库对象
win: any = window;//window对象
constructor( private platform: Platform,
private sqlite: SQLite,
private events: Events,
private storage: StorageServiceProvider) { }
/**
* 创建数据库
*/
createDb() {
if (this.isMobile()) {
this.sqlite.create({
name: 'data.db',
location: 'default'
})
.then((db: SQLiteObject) => {
this.database = db;
//创建表如果已存在就创建
if (this.storage.read('db:create') != "Yes") {
//创建表
this.createTable();
} else {
this.events.publish('db:create');
}
})
.catch(e => {
this.showAlert(this.text.CREATE_DB);
this.events.publish('db:create');
});
} else {
//H5数据库存储,注意测试浏览器兼容,websql w3c没维护
try {
this.win_db = this.win.openDatabase("data.db", '1.0', 'database', 5 * 1024 * 1024);//声明H5 数据库大小
this.createTable();
} catch (err) {
console.log('创建数据库失败')
}
}
}
/**
* 创建表
*/
async createTable() {
// this.querySql('', []);
//可能存在多个执行创建表语句,只需最后一个使用await
await this.executeSql('CREATE TABLE remindMaster(remind_id INTEGER PRIMARY KEY AUTOINCREMENT,user_id TEXT,state TEXT , content TEXT,remind_time TEXT,create_time TEXT)', []);
this.events.publish('db:create');
this.storage.write('db:create', "Yes");
}
/**
* 执行语句
*/
executeSql(sql: string, array: Array): Promise {
return new Promise((resolve, reject) => {
if (this.isMobile()) {
if (!!!!this.database) {
this.database.executeSql(sql, array).then((data) => {
resolve(data);
}, (err) => {
reject(err);
console.log('Unable to execute sql: ' + err);
});
} else {
return new Promise((resolve) => {
resolve([]);
});
}
} else {
if (this.win_db) {
return this.execWebSql(sql, array).then(data => {
resolve(data);
}).catch(err => {
console.log(err);
});
}
}
});
}
/**
* 查询H5数据库
*/
execWebSql(sql: string, params: Array): Promise {
return new Promise((resolve, reject) => {
try {
this.win_db.transaction((tx) => {
tx.executeSql(sql, params,
(tx, res) => resolve(res),
(tx, err) => reject(err));
},
(err) => reject(err));
} catch (err) {
reject(err);
}
});
}
/**
* 是否真机环境
* @return {boolean}
*/
isMobile(): boolean {
return this.platform.is('mobile') && !this.platform.is('mobileweb');
}
}
3. 调用
删除app.html里的默认root属性
在程序初始化的时候调用创建数据库(即app.component.ts里)
constructor(
private statusBar: StatusBar,
private splashScreen: SplashScreen,
private nativeProvider: NativeProvider) {
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
this.init();//初始化
});
}
init(){
//确保异步执行完后才隐藏启动动画
this.events.subscribe('db:create', () => {
//创建数据库与表成功后才关闭动画跳转页面
this.statusBar.styleDefault();
this.splashScreen.hide();
this.nav.setRoot(TabsPage);
})
//初始化创建数据库
this.nativeProvider.createDb();
}
在所需页面引入调用即可
//插入数据
this.nativeProvider.executeSql('INSERT INTO remindMaster(user_id,state,content,remind_time,create_time) VALUES (?,?,?,?,?)',
['1', '0', 'haha', '2017-12-14', new Date().getTime().toString()]);
//查询数据
//如果使用直接拼接sql查询,需要注意参数加 '',否则真机sqlite查看不到数据 例如:(`SELECT remind_id,state,user_id,content,remind_time,create_time FROM remindMaster WHERE state='0' AND user_id = '${user_id }' ORDER BY remind_time ASC`, []
this.nativeProvider.executeSql('SELECT remind_id,state,user_id,content,remind_time,create_time FROM remindMaster WHERE state=? AND user_id = ? ORDER BY remind_time ASC', ['0','1']).then(data => {
if (!!!!data && !!!!data.rows && data.rows.length > 0) {
for (let i = 0; i < data.rows.length; i++) {
console.log(data.rows.item(i));
}
}
});