安裝插件
- 安裝sqlite插件和依賴
npm install --save @ionic-native/sqlite
ionic cordova plugin add cordova-sqlite-storage
在app.moudle.ts中引入SQLite
...
import { SQLite } from '@ionic-native/sqlite';
...
providers: [
...
SQLite
]
...
封裝SQLService服務(wù)類
封裝服務(wù)類默责,每次執(zhí)行sql語句都調(diào)用SQLService的方法
SQLService代碼:
import { Injectable } from '@angular/core';
//原生插件
import { SQLite, SQLiteObject, SQLiteTransaction } from '@ionic-native/sqlite';
//自定義服務(wù)
import { NativeService } from "./NativeService";
import { SQLITE } from './Constants';
/**
* SQLite數(shù)據(jù)庫
* @export
* @class SQLService
*/
@Injectable()
export class SQLService {
//window對(duì)象
private win: any = window;
//數(shù)據(jù)庫對(duì)象
private database: SQLiteObject;
//是否android環(huán)境
private isAndroid: boolean;
constructor(private sqlite: SQLite, private nativeService: NativeService) {
this.isAndroid = this.nativeService.isAndroid();
}
/**
* 自動(dòng)判斷環(huán)境創(chuàng)建sqlite數(shù)據(jù)庫
* @memberof SQLService
*/
public initDB()
{
if (!this.win.sqlitePlugin)
{
//window.openDatabase("數(shù)據(jù)庫名字", "版本","數(shù)據(jù)庫描述",數(shù)據(jù)庫大小);
this.database = this.win.openDatabase(SQLITE.WINDOW.name, SQLITE.WINDOW.version,
SQLITE.WINDOW.describe, SQLITE.WINDOW.maxSize);
return;
}
if (this.isAndroid)
{
this.sqlite.create({
name: SQLITE.ANDROID.name,
location: SQLITE.ANDROID.location
}).then((db) => {
this.database = db;
}).catch(err => {
console.log(err);
});
}
else
{
this.sqlite.create({
name: SQLITE.IOS.name,
iosDatabaseLocation: SQLITE.IOS.iosDatabaseLocation,
}).then((db) => {
this.database = db;
}).catch(err => {
console.log(err);
});
}
}
/**
* 執(zhí)行sql語句
* @param {string} sql
* @param {*} [params={}]
* @returns {Promise<any>}
* @memberof SQLService
*/
executeSql(sql: string, params: any = []): Promise<any>
{
return new Promise((resolve, reject) => {
try
{
this.database.transaction((tx: SQLiteTransaction) => {
tx.executeSql(sql, params, (tx, res) => {
resolve({tx: tx, res: res});
}, (tx, err) => {
reject({tx: tx, err: err});
});
});
}
catch (err)
{
reject({err: err});
}
});
}
}
ps: 因?yàn)槲业拇a類與類之間相互依賴秧荆,所以就不一一羅列揍诽,只貼出核心代碼顶滩,直接復(fù)制代碼會(huì)出現(xiàn)報(bào)錯(cuò)情況损谦,請自行修改磅网。
其中用到的NativeService的方法:
NativeService用到的代碼:
/**
* 是否是真機(jī)環(huán)境
* @returns {boolean}
* @memberof NativeService
*/
isMobile(): boolean
{
return this.platform.is("mobile") && !this.platform.is("mobileweb");
}
/**
* 是否android真機(jī)環(huán)境
* @returns {boolean}
* @memberof NativeService
*/
isAndroid(): boolean
{
return this.isMobile() && this.platform.is("android");
}
使用SQLite
- 在
app.component.ts
文件中導(dǎo)入SQLService依賴
- 調(diào)用
this.sqlService.initDB()
初始化SQLite數(shù)據(jù)庫 - 在要使用數(shù)據(jù)庫的地方使用
this.sqlService.executeSql(sql)
如圖:
代碼:
createTable()
{
let sql = 'create table IF NOT EXISTS user(id VARCHAR(32), name VARCHAR(64), sex NUMBER(8))';
this.sqlService.executeSql(sql).then((data) => {
console.log(data);
}).catch((err) => {
console.log(err)
});
}
deleteTable()
{
let sql = 'drop table user';
this.nativeService.confirm('確定要?jiǎng)h除user表嗎婚惫?', '', () => {
this.sqlService.executeSql(sql).then((data) => {
console.log(data);
}).catch((err) => {
console.log(err)
});
});
}
insertUser()
{
let id = Utils.getSequence();
let sql = "insert into user values('"+ id +"', 'JoyoDuan" + id + "', 23)";
this.sqlService.executeSql(sql).then((data) => {
console.log(data);
}).catch((err) => {
console.log(err)
});
}
其中this.nativeService.confirm()是我自己封裝的alert方法屡谐。
this.nativeService.confirm()
代碼
/**
* [確認(rèn)框]
* @param {string} message [消息]
* @param {string} title [標(biāo)題]
* @param {any[]) => void} confirmHandler [確認(rèn)操作]
* @param {any[]) => void} cancelHandler [取消操作]
*/
confirm(message: string, title?: string, confirmHandler?: (...args: any[]) => void, confirmText?: string,
cancelHandler?: (...args: any[]) => void)
{
let confirm = this.alertCtrl.create({
title: title ? title : this.title,
message: message,
buttons:[
{
text:"取消",
role: "cancel",
handler: () => {
if(cancelHandler) cancelHandler();
}
},
{
text: confirmText || "確定",
handler: () => {
if(confirmHandler) confirmHandler();
}
}
],
cssClass: "alert"
});
confirm.present();
}