· 9 years ago · Nov 03, 2016, 09:46 AM
1ionic plugin add cordova-sqlite-storage
2
3ionic g provider nameOfYourProvider
4
5import {Sql} from '../providers/Sql';
6
7import {Sql} from '../providers/Sql';
8...
9...
10providers: [Sql]
11
12import { Injectable } from '@angular/core';
13import { Platform } from 'ionic-angular';
14
15const DB_NAME: string = '__ionicstorage';
16const win: any = window;
17
18@Injectable()
19export class Sql {
20 private _db: any;
21
22 constructor(public platform: Platform) {
23 this.platform.ready().then(() => {
24 if (win.sqlitePlugin) {
25 this._db = win.sqlitePlugin.openDatabase({
26 name: DB_NAME,
27 location: 2,
28 createFromLocation: 0
29 });
30 } else {
31 console.warn('Storage: SQLite plugin not installed, falling back to WebSQL.');
32 this._db = win.openDatabase(DB_NAME, '1.0', 'database', 5 * 1024 * 1024);
33 }
34 this._tryInit();
35 });
36 }
37
38 // Initialize the DB with our required tables
39 _tryInit() {
40 this.query('CREATE TABLE IF NOT EXISTS kv (key text primary key, value text)').catch(err => {
41 console.error('Storage: Unable to create initial storage tables', err.tx, err.err);
42 });
43 }
44
45 /**
46 * Perform an arbitrary SQL operation on the database. Use this method
47 * to have full control over the underlying database through SQL operations
48 * like SELECT, INSERT, and UPDATE.
49 *
50 * @param {string} query the query to run
51 * @param {array} params the additional params to use for query placeholders
52 * @return {Promise} that resolves or rejects with an object of the form { tx: Transaction, res: Result (or err)}
53 */
54 query(query: string, params: any[] = []): Promise<any> {
55 return new Promise((resolve, reject) => {
56 try {
57 this._db.transaction((tx: any) => {
58 tx.executeSql(query, params,
59 (tx: any, res: any) => resolve({ tx: tx, res: res }),
60 (tx: any, err: any) => reject({ tx: tx, err: err }));
61 },
62 (err: any) => reject({ err: err }));
63 } catch (err) {
64 reject({ err: err });
65 }
66 });
67 }
68
69 /**
70 * Get the value in the database identified by the given key.
71 * @param {string} key the key
72 * @return {Promise} that resolves or rejects with an object of the form { tx: Transaction, res: Result (or err)}
73 */
74 get(key: string): Promise<any> {
75 return this.query('select key, value from kv where key = ? limit 1', [key]).then(data => {
76 if (data.res.rows.length > 0) {
77 return data.res.rows.item(0).value;
78 }
79 });
80 }
81
82 /**
83 * Set the value in the database for the given key. Existing values will be overwritten.
84 * @param {string} key the key
85 * @param {string} value The value (as a string)
86 * @return {Promise} that resolves or rejects with an object of the form { tx: Transaction, res: Result (or err)}
87 */
88 set(key: string, value: string): Promise<any> {
89 return this.query('insert or replace into kv(key, value) values (?, ?)', [key, value]);
90 }
91
92 /**
93 * Remove the value in the database for the given key.
94 * @param {string} key the key
95 * @return {Promise} that resolves or rejects with an object of the form { tx: Transaction, res: Result (or err)}
96 */
97 remove(key: string): Promise<any> {
98 return this.query('delete from kv where key = ?', [key]);
99 }
100}
101
102import {Sql} from '../../providers/Sql';
103
104export class ExamplePage {
105 constructor(private sql: Sql) {
106 //sql.query(...);
107
108 //...
109 }
110}