和尚在很久之前尝试过 SQL 数据库的应用,但在实际场景中用到的比较少,一直没有后续研究;今天和尚根据实际应用对 SQL 进行一个简单的小封装;
和尚继续采用 sqflite 插件来完成对数据库的操作;
根据这两条要求,和尚分为两步,第一步提取公共的抽象类,以供给多个表类型操作;第二步是针对具体表采用单例方式进行操作;
对于数据库表的操作,其根本就是增删改查,和尚仅对公共的方法进行抽象类的提取;和尚提取了多张表中均需要的分页查询或根据 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();
}
对于单张表的操作,使用单例会方便很多,可以在全局使用;之后在单独实现提取的抽象类;
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;
}
}
和尚在刚开始初始化连接数据库时,提示 join() 方法找不到;其原因是和尚只引入了 package:sqflite/sqflite.dart,还需要引入 package:path/path.dart,这个引入不会自动提醒需要注意;
和尚在做实体类转 Map 类型时遇到类型不匹配,其原因是和尚在定义 BillBean.toMap() 时需要指定 Map 与数据库存储时类型匹配即可;也可以通过 Map.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
});
和尚在调用更新和删除数据库表内容时,调用 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 案例源码
和尚对于数据库的小封装还不够完善,仅根据业务等进行部分抽离等,后续会根据业务继续完善;如有错误请多多指导!
来源:阿策小和尚