Flutter 111: 圖解關乎 SQL 數據庫的二三事 (二) 之【小封裝】

    小菜在很久之前嘗試過 SQL 數據庫的應用,但在實際場景中用到的比較少,一直沒有後續研究;今天小菜根據實際應用對 SQL 進行一個簡單的小封裝;

SQL

    小菜繼續採用 sqflite 插件來完成對數據庫的操作;

  • 小菜需要對多個表操作,針對不同的表有相同方法
  • 對於單張表在多個頁面需要操作

    根據這兩條要求,小菜分爲兩步,第一步提取公共的抽象類,以供給多個表類型操作;第二步是針對具體表採用單例方式進行操作;


1. 提取抽象類

    對於數據庫表的操作,其根本就是增刪改查,小菜僅對公共的方法進行抽象類的提取;小菜提取了多張表中均需要的分頁查詢或根據 Map / Json 方式插入更新數據庫表等;

abstract class SQLMethod {
  /// 根據SQL插入一條數據
  /// [sql]         插入SQL
  Future<int> insertSQL(String sql);

  /// 根據Map插入一條數據
  /// [tableName]   表名
  /// [map]         插入Map
  Future<int> insertByMap(String tableName, Map<String, dynamic> map);

  /// 根據Map插入一條數據
  /// [tableName]   表名
  /// [json]         插入Json
  Future<int> insertByJson(String tableName, String json);

  /// 根據key-value刪除一條數據
  /// [tableName]   表名
  /// [key]         鍵-ColumnName
  /// [value]       值-ColumnValue
  Future<int> deleteByParams(String tableName, String key, Object value);

  /// 刪除表內所有數據
  /// [tableName]   表名
  Future<int> deleteAll(String tableName);

  /// 根據SQL更新數據
  /// [tableName]   表名
  /// [sql]         更新SQL
  updateSQL(String tableName, String sql);

  /// 根據Map更新一條數據
  /// [tableName]   表名
  /// [map]         更新Map
  updateByMap(String tableName, Map<String, dynamic> map);

  /// 查詢固定數量數據列表
  /// [tableName]   表名
  /// [count]       數量
  /// [orderBy]     升序/降序
  Future<List<Map<String, dynamic>>> queryList(String tableName,
      {int count, String orderBy});

  /// 分頁查詢數據列表
  /// [tableName]   表名
  /// [orderBy]     升序/降序
  /// [limitCount]  每頁數據長度
  /// [pageSize]    當前頁碼
  Future<List<Map<String, dynamic>>> queryListByPage(
      String tableName, int limitCount, int pageSize,
      {String orderBy});

  /// 關閉數據庫
  closeDB();
}

2. 單例

    對於單張表的操作,使用單例會方便很多,可以在全局使用;之後在單獨實現提取的抽象類;

class BillSQLManager extends SQLMethod {
  static BillSQLManager _instance;
  Database _db;

  static BillSQLManager getInstance() {
    if (_instance == null) {
      _instance = new BillSQLManager();
    }
    return _instance;
  }
}

初始化數據庫

Future<Database> initDB() async {
  final databasePath = await getDatabasesPath();
  print('SQLManager.initDB -> databasePath = $databasePath');
  final path = join(databasePath, ConstantUtils.DB_NAME);
  _db = await openDatabase(path,
      version: ConstantUtils.DB_VERSION,
      onCreate: (_db, _) => _db.execute(ConstantUtils.CREATE_BILL_SQL));
  return _db;
}

插入數據庫

@override
Future<int> insertByMap(String tableName, Map<String, dynamic> map) async {
  int result;
  if (map != null) {
    result = await _db.insert(tableName, map);
  }
  return result;
}

查詢數據庫

@override
Future<List<Map<String, dynamic>>> queryList(String tableName, {int count, String orderBy}) async {
  List<Map<String, dynamic>> list = await _db.query(tableName, orderBy: 'updateTime ${orderBy ?? 'DESC'}');
  if (list != null) {
    if (count != null && count > 0) {
      if (count >= list.length) {
        return list;
      } else {
        return list.sublist(0, count);
      }
    } else {
      return list;
    }
  }
  return null;
}

更新數據庫

@override
updateByParams(String tableName, String key, Object value, Map<String, dynamic> map) async {
  if (key != null) {
    return await _db.update(tableName, map, where: '$key=?', whereArgs: [value]);
  }
  return null;
}

刪除數據庫

@override
Future<int> deleteByParams(String tableName, String key, Object value) async {
  if (key != null) {
    return await _db.delete(tableName, where: '$key=?', whereArgs: [value]);
  } else {
    return -1;
  }
}

3. 注意事項

1. join() 方法找不到

    小菜在剛開始初始化連接數據庫時,提示 join() 方法找不到;其原因是小菜只引入了 package:sqflite/sqflite.dart,還需要引入 package:path/path.dart,這個引入不會自動提醒需要注意;

2. Unhandled Exception: type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<String, dynamic>'

    小菜在做實體類轉 Map 類型時遇到類型不匹配,其原因是小菜在定義 BillBean.toMap() 時需要指定 Map<String, dynamic> 與數據庫存儲時類型匹配即可;也可以通過 Map<String, dynamic>.from(map) 轉換一下即可;

map = Map<String, dynamic>.from({
  'billName': _tableController.text.trim(),
  'billExp': '0.0',
  'billInc': '0.0',
  'billCount': '0',
  'createTime': DateTime.now().millisecondsSinceEpoch,
  'updateTime': DateTime.now().millisecondsSinceEpoch
});

3. whereArgs 如何傳參

    小菜在調用更新和刪除數據庫表內容時,調用 update 時,通過 whereArgs 傳參時,參數會自動加入到 map 中,其原因時小菜直接通過 where 進行判斷是設置了 key=value 後又使用了 whereArgs,可以通過 $key=? 來調用;

// 方式一:
updateByParams(String tableName, String key, Object value, Map<String, dynamic> map) async {
  if (key != null) {
    return await _db.update(tableName, map, where: '$key=?', whereArgs: [value]);
  }
  return null;
}

// 方式二:
updateByParams(String tableName, String key, Object value, Map<String, dynamic> map) async {
  if (key != null) {
    return await _db
        .update(tableName, map, where: '$key=¥value');
  }
  return null;
}

    SQL 案例源碼


    小菜對於數據庫的小封裝還不夠完善,僅根據業務等進行部分抽離等,後續會根據業務繼續完善;如有錯誤請多多指導!

來源: 阿策小和尚

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章