美文网首页
Cordova + Ionic3 下 SQLCipher 的封装

Cordova + Ionic3 下 SQLCipher 的封装

作者: 环零弦 | 来源:发表于2018-04-10 13:30 被阅读0次

需求:

SQLCipher 封装成一个服务,同时加入优化的设置。

代码:

服务类:SqliteService.ts
import {Injectable} from "@angular/core";

declare let window: any;

@Injectable()
export class SqliteService {

  private db = null;
  private dbConfig = {
    name: 'demo.db',
    // key: '1234',
    location: 'default'
  };

  constructor() {
    document.addEventListener('deviceready', () => {
      this._openDatabase();
    });
  }

  private _openDatabase() {
    this.db = window.sqlitePlugin.openDatabase(this.dbConfig);
    this.db.executeSql('PRAGMA synchronous = OFF;');
  }

  public rdTransaction(statements: Array<any>): Promise<any> {
    !this.db && this._openDatabase();
    const finalResultSet = [];
    return new Promise(resolve => {
      this.db.transaction(tx => {
        for (let index = 0, len = statements.length; index < len; index++) {
          let params = [];
          if (Array.isArray(statements[index])) {
            params = statements[index][1];
            statements[index] = statements[index][0];
          }
          tx.executeSql(statements[index], params, (tx, rs) => {
            finalResultSet[index] = rs;
          }, (tx, error) => {
            console.log(JSON.stringify(error.message));
          });
        }
      }, error => {
        console.log('Transaction ERROR: ' + error.message);
        resolve(error);
      }, () => {
        console.log('Populated database OK');
        resolve(finalResultSet);
      });
    });
  }

  public rdExecuteSql(statement: any): Promise<any> {
    !this.db && this._openDatabase();
    let params = [];
    if (Array.isArray(statement)) {
      params = statement[1];
      statement = statement[0];
    }
    return new Promise(resolve => {
      this.db.executeSql(statement, params, rs => {
        resolve(rs);
      }, error => {
        resolve(error);
      });
    });
  }
}
使用类 home.ts
document.addEventListener('deviceready', () => {
  const statements = [
    'CREATE TABLE IF NOT EXISTS DemoTable (name, score);',
    ['INSERT INTO DemoTable VALUES (?,?);', ['Alice', 101]],
    ['INSERT INTO DemoTable VALUES (?,?);', ['Betty', 202]],
  ];
  const statement = 'SELECT * FROM DemoTable;';
  this.sqliteService.rdTransaction(statements).then(rs => {
    // this.updateTextArea(JSON.stringify(rs) + '\n');
    this.sqliteService.rdExecuteSql(statement).then(rs => {
      for (let index = 0, len = rs.rows.length; index < len; index++) {
        this.updateTextArea(JSON.stringify(rs.rows.item(index)));
      }
    });
  });
});

参考资料:

相关文章

网友评论

      本文标题:Cordova + Ionic3 下 SQLCipher 的封装

      本文链接:https://www.haomeiwen.com/subject/nmoghftx.html