欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

websql操作类封装

程序员文章站 2022-12-21 11:02:58
在之前,我写了一个websql的封装类库,代码如下: (function(win) { function smpWebSql(options){ options = options || {}; this.database = null; this.DateBaseName = options.Da ......

  在之前,我写了一个websql的封装类库,代码如下:

(function(win) {
    function smpwebsql(options){
        options = options || {};
        this.database = null;
        this.datebasename = options.datebasename || 'smpdb';
        this.version = options.version || '1.0';
        this.description = options.description || 'smpdb';
        this.databasesize = options.databasesize || 2 * 1024 * 1024;
        this.init();
    }
    smpwebsql.prototype = {
        init: function() {
            this.database = opendatabase(this.datebasename, this.version, this.description, this.databasesize); //初始化数据库
        },
        addblob: function (tablename, arr,index,isfirst,callback) {//批量添加字段
            /*
                注 : 数据里面的第一个key存储类型为blob
                @param  tablename 表名
                @param  arr 更新的数据    [{key1:value1 , key2 : value2 ...},{key1:value1 , key2 : value2 ...}]
                @param  index blog字段所在的索引位置
                @param  isfirst 是否是第一次创建表
                @param  callback  回调
             */
            if (arr == null) {
                return this;
            }
            callback = this.isfunction(callback) ? callback : new function();
            var _me = this,
                _db = this.database,
                keyc = [],
                keyi = [],
                _key = '';
            arr = arr || [];
            if (arr && arr.constructor == array) {
                for (var i in arr[0]) {
                    keyc.push(i);
                    keyi.push(i);
                }
                _key = keyi.join(",");
                index = index == undefined ? 0 : index;
                keyc[index] = keyc[index] + ' blob';
                _db.transaction(function (tx, result) {
                    //var csql = 'create table if not exists ' + tablename + ' (' + keyc.join(",") + ')';
                    //console.log('csql:' + csql);
                    if (isfirst == true) {
                        tx.executesql('create table if not exists ' + tablename + ' (' + keyc.join(",") + ')');
                    }
                    //var sql = "";
                    for (var s = 0, _len = arr.length; s < _len ; s++) {
                        var _value = _me.split(arr[s]);
                        //sql += 'insert into ' + tablename + ' (' + _key + ') values (' + _value + ')';
                        //console.log("sql:" + sql);
                        tx.executesql('insert into ' + tablename + ' (' + _key + ') values (' + _value + ')',[],function (tx, result) {
                            callback(result.rowsaffected);
                            //console.log('添加成功'+result.rowsaffected);
                        },function (tx, error) {
                            console.error('添加失败');
                            callback(false);
                        });
                    }
                    _key = keyi = keyc = null;
                    callback();
                });
            }
            return this;
        },
        add: function (tablename, arr, callback, nokey) {//批量添加字段
            /*
                注 : 数据里面的第一个key 为主键
                @param  tablename 表名
                @param  arr 更新的数据    [{key1:value1 , key2 : value2 ...},{key1:value1 , key2 : value2 ...}]
                @param  callback  回调
                @param  nokey 第一个字段是否是主键(默认是)
             */
            if(arr==null){
                return this;
            }
            callback = this.isfunction(callback) ? callback : new function();
            var _me = this,
                _db = this.database,
                keyc = [],
                keyi = [],
                _key = '';
            arr = arr || [];
            if (arr && arr.constructor == array) {
                for(var i in arr[0]){
                    keyc.push(i);
                    keyi.push(i);
                }
                if (nokey==undefined) {
                    keyc[0] = keyc[0] + ' unique';
                }
                _key = keyi.join(",");
                _db.transaction(function (tx) {
                   ///var csql = 'create table if not exists ' + tablename + ' (' + keyc.join(",") + ')';
                    // console.log('csql:' + csql);
                     tx.executesql('create table if not exists ' + tablename + ' (' + keyc.join(",") + ')');
                    //var sql = "";
                    for(var s = 0 , _len = arr.length; s < _len ; s++){
                        var _value = _me.split(arr[s]);
                        //sql += 'insert into ' + tablename + ' (' + _key + ') values (' + _value + ')';
                        //console.log("sql:" + sql);
                        tx.executesql('insert into '+tablename+' ('+_key+') values ('+_value+')',[],function (tx, result) {
                            callback(result.rowsaffected);
                            //console.log('添加成功'+result.rowsaffected);
                        },function (tx, error) {
                            console.error('添加失败');
                            callback(false);
                        });
                    }
                    _key = keyi = keyc = null;
                    callback();
                });
            }
            return this;
        },
        update : function(tablename,key,value,obj,callback){//更新指定数据
            /*
                @param  tablename 表名
                @param  key 查询的键 
                @param  value 对应键的值
                @param  obj 更新的数据    {key1:value1 , key2 : value2 ...} 
                @param  callback  回调  传递参数为真则查询成功 反之更新失败
             */
            callback = this.isfunction(callback) ? callback : new function();
            var _db = this.database,
                _value = this.splitu(obj);
            _db.transaction(function (tx) {
                //console.log('sql:' + 'update ' + tablename + ' set ' + _value + ' where ' + key + '="' + value + '"')
                tx.executesql('update '+tablename+' set '+_value+' where '+key+'="'+value+'"',[],function (tx, result) {
                    callback(result.rowsaffected);
                },function (tx, error) {
                    console.error('更新失败');
                    callback(false);
                });
            });
            return this;
        },
        updatewhere: function (tablename, where, obj, callback) {//更新指定数据
            /*
                @param  tablename 表名
                @param  查询条件 
                @param  obj 更新的数据    {key1:value1 , key2 : value2 ...} 
                @param  callback  回调  传递参数为真则查询成功 反之更新失败
             */
            callback = this.isfunction(callback) ? callback : new function();
            var _db = this.database,
                _value = this.splitu(obj);
            _db.transaction(function (tx) {
                console.log('update ' + tablename + ' set ' + _value + ' where ' + where + '"')
                tx.executesql('update ' + tablename + ' set ' + _value + ' where ' + where + '"', [], function (tx, result) {
                    callback(result.rowsaffected);
                }, function (tx, error) {
                    console.error('更新失败');
                    callback(false);
                });
            });
            return this;
        },
        read : function(tablename,condition,callback){ //读取表数据
            /*
                @param  tablename 表名
                @param  condition 查询条件   'where name="汪文君"'
                @param  callback  回调  传递参数为真则查询成功 反之查询失败
             */
            var _condition = this.isstring(condition) ? condition : '';
            var _callback = this.isfunction(condition) ? condition : this.isfunction(callback) ? callback : new function;
            var _db = this.database,
                _me = this,
                _re = [];
                _db.transaction(function (tx) {
                    tx.executesql('select * from ' + tablename + ' ' + _condition + ' ', [], function (tx, results) {
                        if(results && results.rows){
                            _re =_me.toarray(results.rows);
                            _callback(_re);
                        }else{
                            _callback([]);
                        }
                    },function(tx,error){
                        _callback([]);
                        console.error('查询失败');
                    });
                });
                return this;
        },
        remove:function(tablename,condition,callback){//删除数据
            /*
                @param  tablename 表名
                @param  condition 查询条件   'where name="汪文君"'
                @param  callback  回调  传递参数为真则删除成功 反之删除失败
             */
            var _me = this;
            var _condition = this.isstring(condition) ? condition : '';
            var _callback = this.isfunction(condition) ? condition : this.isfunction(callback) ? callback : new function;
            _me.database.transaction(function (tx) {
                tx.executesql('delete from '+tablename+ ' '+ _condition+' ',[],function (tx, result) {
                    _callback(result.rowsaffected);
                },function (tx, error) {
                    _callback(false);
                    console.error('删除失败');
                });
            });
        },
        counts: function (tablename, condition, callback) { //读取表数据
            /*
                @param  tablename 表名
                @param  condition 查询条件   'where name="汪文君"'
                @param  callback  回调  传递参数为真则查询成功 反之查询失败
             */
            var _condition = this.isstring(condition) ? condition : '';
            var _callback = this.isfunction(condition) ? condition : this.isfunction(callback) ? callback : new function;
            var _db = this.database,
                _me = this,
                _re = [];
            if (mui.os.ios) { //ios下面特有的
                _db.transaction(function (tx) {
                    tx.executesql('select no from ' + tablename + ' ' + _condition + ' ', [], function (tx, results) {// count (*) as num
                        if (results && results.rows) {
                            _re = _me.toarray(results.rows);
                            _callback(_re.length);
                        } else {
                            _callback(0);
                        }
                    }, function (tx, error) {
                        _callback(0);
                        console.error('查询失败');
                    });
                });
            } else {
                _db.transaction(function (tx) {
                    tx.executesql('select count (*) as num from ' + tablename + ' ' + _condition + ' ', [], function (tx, results) {// count (*) as num
                        if (results && results.rows) {
                            if (results.rows[0]) {
                                _callback(results.rows[0].num);
                            } else {
                                _callback(0);
                            }
                        } else {
                            _callback(0);
                        }
                    }, function (tx, error) {
                        _callback(0);
                        console.error('查询失败');
                    });
                });
            }
            return this;
        },
        deltable:function(tablename,callback){ //删除数据表
            callback = this.isfunction(callback) ? callback : new function();
            this.database.transaction(function(tx){
                tx.executesql('drop table if exists '+tablename,[],function(tx,res){
                    callback();
                },function(tx,err){
                    console.error(err);
                });
            });
            return this;
        },
        splitu: function(obj){//更新字符处理
            var _arr = [];
            for(var t in obj){
                _arr.push(t+'="'+obj[t]+'"');
            }
            return _arr.join(',');
        },
        split : function(obj){//添加字符处理
            var _arr = [];
            for(var m in obj){
                _arr.push("'"+obj[m]+"'");
            }
            return _arr.join(',');
        },
        isfunction : function(callback){
            return typeof callback != 'undefined' && callback.constructor == function ? true : false
        },
        isstring : function(string){
            return typeof string == 'string' ? true : false
        },
        toarray : function(obj){
            var _arr = [],
                _len = obj.length;
                if(_len > 0){
                    for (var i = 0; i < _len; i++) {
                        _arr.push(obj.item(i));
                    };
                }
                return _arr;
        }
    }
    win.smpwebsql = smpwebsql;
}(window))

  上述代码存在的问题非常明显,由于websql操作都是异步操作,当我们为了获取到websql操作的结果之后再进行后续操作时,往往是通过回调函数来实现的,当回调一多的时候,回调地狱就出现了,为了解决回调地狱问题,我将通过promise来改写,后续调用时,可以直接通过await和async来调用,或者直接通过promise链式调用也是可以的。

  现在我将通过es6的语法重写之前的封装类,为了应用es6中js面向对象的思想,我这里用到了class,最终代码如下:

import utils from '@/utils/utils.js';
class smpwebsql {
  constructor(options) {
    options = options || {};
    this.database = null;
    this.datebasename = options.datebasename || 'reddb';
    this.version = options.version || '1.0';
    this.description = options.description || '智维离线工单数据库';
    this.databasesize = options.databasesize || 2 * 1024 * 1024;
    this.init();
  }
  /**
   * 初始化数据库
   */
  init() {
    this.database = opendatabase(
      this.datebasename,
      this.version,
      this.description,
      this.databasesize
    );
  }
  /**
   * 批量添加字段
   * @param {*} tablename 表名
   * @param {*} arr 更新的数据    [{key1:value1 , key2 : value2 ...},{key1:value1 , key2 : value2 ...}]
   * @param {*} index blog字段所在的索引位置
   * @param {*} isfirst 是否是第一次创建表
   */
  addblob(tablename, arr, index, isfirst) {
    var _db = this.database;
    var _me = this;
    // eslint-disable-next-line promise/param-names
    return new promise(function(resovle, reject) {
      if (arr == null) {
        return this;
      }
      var keyc = [];
      var keyi = [];
      var _key = '';
      arr = arr || [];
      if (arr && arr.constructor == array) {
        for (var i in arr[0]) {
          keyc.push(i);
          keyi.push(i);
        }
        _key = keyi.join(',');
        index = index == undefined ? 0 : index;
        keyc[index] = keyc[index] + ' blob';
        // eslint-disable-next-line promise/param-names

        _db.transaction(function(tx, result) {
          // var csql = 'create table if not exists ' + tablename + ' (' + keyc.join(",") + ')';
          // console.log('csql:' + csql);
          if (isfirst == true) {
            tx.executesql(
              'create table if not exists ' +
                tablename +
                ' (' +
                keyc.join(',') +
                ')'
            );
          }
          // var sql = "";
          for (var s = 0, _len = arr.length; s < _len; s++) {
            var _value = _me.split(arr[s]);
            // sql += 'insert into ' + tablename + ' (' + _key + ') values (' + _value + ')';
            // console.log("sql:" + sql);
            tx.executesql(
              'insert into ' +
                tablename +
                ' (' +
                _key +
                ') values (' +
                _value +
                ')',
              [],
              function(tx, result) {
                resovle(result.rowsaffected);
                // console.log('添加成功'+result.rowsaffected);
              },
              function(tx) {
                console.error('添加失败');
                // eslint-disable-next-line prefer-promise-reject-errors
                reject(false);
              }
            );
          }
          _key = keyi = keyc = null;
          resovle();
        });
      }
    });
  }
  /**
   * 批量添加字段 注 : 数据里面的第一个key 为主键
   * @param {*} tablename 表名
   * @param {*} arr arr 更新的数据    [{key1:value1 , key2 : value2 ...},{key1:value1 , key2 : value2 ...}]
   * @param {*} nokey nokey 第一个字段是否是主键(默认是)
   */
  add(tablename, arr, nokey) {
    var _me = this;
    var _db = this.database;
    // eslint-disable-next-line promise/param-names
    return new promise(function(resovle, reject) {
      if (arr == null) {
        return this;
      }
      var keyc = [];
      var keyi = [];
      var _key = '';
      arr = arr || [];
      if (arr && arr.constructor == array) {
        for (var i in arr[0]) {
          keyc.push(i);
          keyi.push(i);
        }
        if (nokey == undefined) {
          keyc[0] = keyc[0] + ' unique';
        }
        _key = keyi.join(',');
        _db.transaction(function(tx) {
          // /var csql = 'create table if not exists ' + tablename + ' (' + keyc.join(",") + ')';
          // console.log('csql:' + csql);
          tx.executesql(
            'create table if not exists ' +
              tablename +
              ' (' +
              keyc.join(',') +
              ')'
          );
          // var sql = "";
          for (var s = 0, _len = arr.length; s < _len; s++) {
            var _value = _me.split(arr[s]);
            // sql += 'insert into ' + tablename + ' (' + _key + ') values (' + _value + ')';
            // console.log("sql:" + sql);
            tx.executesql(
              'insert into ' +
                tablename +
                ' (' +
                _key +
                ') values (' +
                _value +
                ')',
              [],
              function(tx, result) {
                resovle(result.rowsaffected);
                // console.log('添加成功'+result.rowsaffected);
              },
              function(tx, error) {
                console.error('添加失败');
                // eslint-disable-next-line prefer-promise-reject-errors
                reject(false);
              }
            );
          }
          _key = keyi = keyc = null;
          // resovle();
        });
      }
    });
  }
  /**
   * 更新指定数据
   * @param {*} tablename 表名
   * @param {*} key 查询的键
   * @param {*} value 对应键的值
   * @param {*} obj obj 更新的数据    {key1:value1 , key2 : value2 ...}
   */
  update(tablename, key, value, obj) {
    var _db = this.database;
    var _value = this.splitu(obj);
    // eslint-disable-next-line promise/param-names
    return new promise(function(resovle, reject) {
      _db.transaction(function(tx) {
        // console.log('sql:' + 'update ' + tablename + ' set ' + _value + ' where ' + key + '="' + value + '"')
        tx.executesql(
          'update ' +
            tablename +
            ' set ' +
            _value +
            ' where ' +
            key +
            '="' +
            value +
            '"',
          [],
          function(tx, result) {
            resovle(result.rowsaffected);
          },
          function(tx, error) {
            console.error('更新失败');
            // eslint-disable-next-line prefer-promise-reject-errors
            reject(false);
          }
        );
      });
    });
  }
  /**
   * 更新指定数据
   * @param {*} tablename 表名
   * @param {*} where 查询条件
   * @param {*} obj obj 更新的数据    {key1:value1 , key2 : value2 ...}
   */
  updatewhere(tablename, where, obj) {
    var _db = this.database;
    var _value = this.splitu(obj);
    // eslint-disable-next-line promise/param-names
    return new promise(function(resovle, reject) {
      _db.transaction(function(tx) {
        console.log(
          'update ' + tablename + ' set ' + _value + ' where ' + where + '"'
        );
        tx.executesql(
          'update ' + tablename + ' set ' + _value + ' where ' + where + '"',
          [],
          function(tx, result) {
            resovle(result.rowsaffected);
          },
          function(tx, error) {
            console.error('更新失败');
            // eslint-disable-next-line prefer-promise-reject-errors
            reject(false);
          }
        );
      });
    });
  }
  /**
   * 读取表数据
   * @param {*} tablename 表名
   * @param {*} condition 查询条件   'where name="jiekzou"'
   */
  read(tablename, condition) {
    var _db = this.database;
    var _me = this;
    // eslint-disable-next-line promise/param-names
    return new promise(function(resovle, reject) {
      var _condition = this.isstring(condition) ? condition : '';
      var _re = [];
      _db.transaction(function(tx) {
        tx.executesql(
          'select * from ' + tablename + ' ' + _condition + ' ',
          [],
          function(tx, results) {
            if (results && results.rows) {
              _re = _me.toarray(results.rows);
              resovle(_re);
            } else {
              resovle([]);
            }
          },
          function(tx, error) {
            // eslint-disable-next-line prefer-promise-reject-errors
            reject([]);
            console.error('查询失败');
          }
        );
      });
    });
  }
  /**
   * 删除数据
   * @param {*} tablename 表名
   * @param {*} condition 查询条件   'where name="jiekzou"'
   */
  remove(tablename, condition) {
    var _me = this;
    var _condition = this.isstring(condition) ? condition : '';
    // eslint-disable-next-line promise/param-names
    return new promise(function(resovle, reject) {
      _me.database.transaction(function(tx) {
        tx.executesql(
          'delete from ' + tablename + ' ' + _condition + ' ',
          [],
          function(tx, result) {
            resovle(result.rowsaffected);
          },
          function(tx, error) {
            // eslint-disable-next-line prefer-promise-reject-errors
            reject(false);
            console.error('删除失败');
          }
        );
      });
    });
  }
  /**
   * 根据查询条件读取表记录数
   * @param {*} tablename 表名
   * @param {*} condition 查询条件   'where name="jiekzou"'
   */
  counts(tablename, condition) {
    if (utils.browserversions.android) {
      return this.androidcounts(tablename, condition);
    } else {
      return this.ioscounts(tablename, condition);
    }
  }
  // ios下面特有的
  /**
   * 读取表数据(ios下面特有的)
   * @param {*} tablename 表名
   * @param {*} condition  查询条件   'where name="jiekzou"'
   */
  ioscounts(tablename, condition) {
    var _condition = this.isstring(condition) ? condition : '';
    var _db = this.database;
    var _me = this;
    // eslint-disable-next-line promise/param-names
    return new promise(function(resovle, reject) {
      var _re = [];
      _db.transaction(function(tx) {
        tx.executesql(
          'select no from ' + tablename + ' ' + _condition + ' ',
          [],
          function(tx, results) {
            // count (*) as num
            if (results && results.rows) {
              _re = _me.toarray(results.rows);
              resovle(_re.length);
            } else {
              resovle(0);
            }
          },
          function(tx, error) {
            // eslint-disable-next-line prefer-promise-reject-errors
            reject(0);
            console.error('查询失败');
          }
        );
      });
    });
  }
  /**
   * 读取表数据(android)
   * @param {*} tablename 表名
   * @param {*} condition 查询条件   'where name="jiekzou"'
   */
  androidcounts(tablename, condition) {
    var _condition = this.isstring(condition) ? condition : '';
    var _db = this.database;
    var _me = this;
    // eslint-disable-next-line promise/param-names
    return new promise(function(resovle, reject) {
      var _re = [];
      _db.transaction(function(tx) {
        tx.executesql(
          'select count (*) as num from ' + tablename + ' ' + _condition + ' ',
          [],
          function(tx, results) {
            // count (*) as num
            if (results && results.rows) {
              if (results.rows[0]) {
                resovle(results.rows[0].num);
              } else {
                resovle(0);
              }
            } else {
              resovle(0);
            }
          },
          function(tx, error) {
            // eslint-disable-next-line prefer-promise-reject-errors
            reject(0);
            console.error('查询失败');
          }
        );
      });
    });
  }
  /**
   * 删除数据表
   * @param {*} tablename 表名
   */
  deltable(tablename) {
    // eslint-disable-next-line promise/param-names
    return new promise(function(resovle, reject) {
      this.database.transaction(function(tx) {
        tx.executesql(
          'drop table if exists ' + tablename,
          [],
          function(tx, res) {
            resovle();
          },
          function(tx, err) {
            console.error(err);
            // eslint-disable-next-line prefer-promise-reject-errors
            reject(0);
          }
        );
      });
    });
  }
  // 更新字符处理
  splitu(obj) {
    var _arr = [];
    for (var t in obj) {
      _arr.push(t + '="' + obj[t] + '"');
    }
    return _arr.join(',');
  }
  // 添加字符处理
  split(obj) {
    var _arr = [];
    for (var m in obj) {
      _arr.push('\'' + obj[m] + '\'');
    }
    return _arr.join(',');
  }
  isfunction(callback) {
    return !!(
      typeof callback != 'undefined' && callback.constructor == function
    );
  }
  isstring(string) {
    return typeof string == 'string';
  }
  toarray(obj) {
    var _arr = [];
    var _len = obj.length;
    if (_len > 0) {
      for (var i = 0; i < _len; i++) {
        _arr.push(obj.item(i));
      }
    }
    return _arr;
  }
}

export default smpwebsql;