安装插件
安装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
]
...
app.module.ts.png
封装SQLService服务类
封装服务类,每次执行sql语句都调用SQLService的方法
SQLService.png
SQLService代码:
import { Injectable } from '@angular/core';
//原生插件
import { SQLite, SQLiteObject, SQLiteTransaction } from '@ionic-native/sqlite';
//自定义服务
import { NativeService } from "./NativeService";
import { SQLITE } from './Constants';
/**
* SQLite数据库
* @export
* @class SQLService
*/
@Injectable()
export class SQLService {
//window对象
private win: any = window;
//数据库对象
private database: SQLiteObject;
//是否android环境
private isAndroid: boolean;
constructor(private sqlite: SQLite, private nativeService: NativeService) {
this.isAndroid = this.nativeService.isAndroid();
}
/**
* 自动判断环境创建sqlite数据库
* @memberof SQLService
*/
public initDB()
{
if (!this.win.sqlitePlugin)
{
//window.openDatabase("数据库名字", "版本","数据库描述",数据库大小);
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);
});
}
}
/**
* 执行sql语句
* @param {string} sql
* @param {*} [params={}]
* @returns {Promise}
* @memberof SQLService
*/
executeSql(sql: string, params: any = []): Promise
{
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: 因为我的代码类与类之间相互依赖,所以就不一一罗列,只贴出核心代码,直接复制代码会出现报错情况,请自行修改。
其中用到的NativeService的方法:
nativeService.png
NativeService用到的代码:
/**
* 是否是真机环境
* @returns {boolean}
* @memberof NativeService
*/
isMobile(): boolean
{
return this.platform.is("mobile") && !this.platform.is("mobileweb");
}
/**
* 是否android真机环境
* @returns {boolean}
* @memberof NativeService
*/
isAndroid(): boolean
{
return this.isMobile() && this.platform.is("android");
}
使用SQLite
在app.component.ts文件中导入SQLService依赖
app.component.ts.png
调用this.sqlService.initDB()初始化SQLite数据库
在要使用数据库的地方使用this.sqlService.executeSql(sql)
如图:
使用sqlite.png
代码:
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('确定要删除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方法。
confirm.png
this.nativeService.confirm()代码
/**
* [确认框]
* @param {string} message [消息]
* @param {string} title [标题]
* @param {any[]) => void} confirmHandler [确认操作]
* @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();
}