ionic2 sqlite Service,兼容浏览器和真机

浏览器也可以调试

  • 添加sqlite插件
ionic cordova plugin add cordova-sqlite-storage
npm install --save @ionic-native/sqlite
  • 新建一个SqlService服务
    导入sqlite
    import { SQLite } from '@ionic-native/sqlite';
    判断平台建DB文件:真机用sqlite.create,浏览器用window.openDatabase
    private _db: any;
    private win: any = window;

    constructor(public http: Http, public sqlite: SQLite) {
        if (this.win.sqlitePlugin) {
            this._db = sqlite.create({
                name: 'appdata.db',
                location: 'default'
            });
        } else {
            this._db = this.win.openDatabase("appdata.db", '1.0', 'database', 5 * 1024 * 1024);
        }
    }

执行SQL语句,返回一个承诺

 execSql(sql: string, params = []): Promise<any> {
        return new Promise((resolve, reject) => {
            try {
                this._db.transaction((tx) => {
                        tx.executeSql(sql, params,
                            (tx, res) => resolve({ tx: tx, res: res }),
                            (tx, err) => reject({ tx: tx, err: err }));
                    },
                    (err) => reject({ err: err }));
            } catch (err) {
                reject({ err: err });
            }
        });
    }
  • 使用:在需要使用的页面ts文件里,导入SqlService文件

建表:

  this.sqlService.execSql(obj.sql).then(() => {
                console.info(obj.desc, '表名:', obj.tableName, '创建成功');
            }).catch(err => {
                console.error("出错了", err.error.message);
            });

更新:

    let sql = "update depot set depot_name='" + data.depot_name + "' where depot_no='" + item.depot_no + "'";
                this.sqlService.execSql(sql, []).then(() => {
               
                }).catch((err) => {
                    console.error(err);
                });
            }
其他类似

注意查询的时候,要转换一下才能得到数据

 let output = [];
 let sql = "select * from XXX";
        this.sqlService.execSql(sql, []).then((data) => {
            for (let i = 0; i < data.res.rows.length; i++) {
                output.push(data.res.rows.item(i));
            }
             console.log(output );
        }).catch((err) => {
            console.error(err);
        });
贴出SqlService完整代码
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import { SQLite } from '@ionic-native/sqlite';

@Injectable()
export class SqlService {
    private _db: any;
    private win: any = window;

    constructor(public http: Http, public sqlite: SQLite) {
        if (this.win.sqlitePlugin) {
            this._db = sqlite.create({
                name: 'appdata.db',
                location: 'default'
            });
        } else {
            this._db = this.win.openDatabase("appdata.db", '1.0', 'database', 5 * 1024 * 1024);
        }
    }

    /**
     * 执行SQL语句,返回一个承诺,通过 .then(result=>{}).catch(err=>{})来处理结果
     * @param sql  sql语句
     * @param params sql参数值,可选参数,只有sql语句中用到 ? 传参方式时,params参数值才有效
     */
    execSql(sql: string, params = []): Promise<any> {
        return new Promise((resolve, reject) => {
            try {
                this._db.transaction((tx) => {
                        tx.executeSql(sql, params,
                            (tx, res) => resolve({ tx: tx, res: res }),
                            (tx, err) => reject({ tx: tx, err: err }));
                    },
                    (err) => reject({ err: err }));
            } catch (err) {
                reject({ err: err });
            }
        });
    }

}

    原文作者:YuRi_1
    原文地址: https://www.jianshu.com/p/5829f7f36989
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞