flutter sqlLite工具

分页结果类

import 'package:kittlenapp/module/base/page_param.dart';
import 'package:kittlenapp/utils/base/collection_util.dart';
import 'package:kittlenapp/utils/base/map_util.dart';

///[auth] kittlen
///[description] 分页查询结果

typedef RecordToEmptyFunc<T> = T Function(Map<dynamic, dynamic> oneRecord);

class PageBean<T> {
  /// 当前页
  late int currentPage;

  /// 每页条数
  late int numPerPage;

  ///总条数
  late int totalCount;

  ///数据
  late List<T>? recordList;

  ///分页数
  late int pageCount;

  PageBean(this.currentPage, this.numPerPage, this.totalCount, this.recordList,
      this.pageCount);

  PageBean.from(this.totalCount, this.recordList, PageParam pageParam) {
    currentPage = pageParam.pageNum;
    numPerPage = pageParam.numPerPage;
    pageCount = (totalCount + numPerPage - 1) ~/ numPerPage;
  }

  PageBean.fromByMap(Map map, RecordToEmptyFunc<T> mapToEmptyFunc) {
    List<Map> result = CollectionUtil.toListMap(map['recordList']);
    currentPage = MapUtil.mapGetOrDef(map, 'currentPage', 1);
    numPerPage = MapUtil.mapGetOrDef(map, 'numPerPage', 10);
    totalCount = MapUtil.mapGetOrDef(map, 'totalCount', result.length);
    recordList = result.map((e) => mapToEmptyFunc(e)).toList();
    pageCount = MapUtil.mapGetOrDef(map, 'pageCount', 1);
  }
}

分页入参类

///[auth] kittlen
///[description] 分页参数

class PageParam {
  ///当前页
  int pageNum;

  ///每页条数
  int numPerPage;

  PageParam({this.pageNum = 1, this.numPerPage = 10})
      : assert(pageNum > 0 && numPerPage > 0);

  String toJson() {
    return '{"pageNum":$pageNum,"numPerPage":$numPerPage}';
  }
}

缓存的基础实体

///[auth] kittlen
///[description] 缓存的基础实体
abstract class CacheSqlLiteBaseEntity {
  ///获取表名
  String table();

  ///建表语句
  String createTableSql();

  ///获取id的key
  String getIdKey();

  ///获取id
  String getId();

  ///添加该试题的属性信息
  Map<String, dynamic> toInsertParamsMap();
}

工具

import 'dart:io';

import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:kittlenapp/module/base/cache_sql_lite_base_entity.dart';
import 'package:kittlenapp/module/base/page_bean.dart';
import 'package:kittlenapp/module/base/page_param.dart';
import 'package:kittlenapp/utils/base/collection_util.dart';
import 'package:kittlenapp/utils/base/json_util.dart';
import 'package:kittlenapp/utils/base/log_util.dart';
import 'package:kittlenapp/utils/base/map_util.dart';
import 'package:sqflite/sqflite.dart';
import 'package:sqflite_common/src/value_utils.dart';

///[auth] kittlen
///[description] sqlLite工具类

///自定义sql运行
typedef CustomDbRum<T> = Future<T> Function(DBManager);

///结果转换成对象
typedef ResultToEntity<T> = T Function(Map);

class SqlLiteUtil {
  static final DBManager _dbManager = DBManager()
    ..db.then((value) {
      LogUtil.debug("sqlLite: db初始化完成");
    });

  ///事务执行
  static Future<T> transaction<T>(Future<T> Function(Transaction txn) action, {bool? exclusive}) async {
    return _dbManager.transaction(action, exclusive: exclusive);
  }

  ///自定义执行
  ///[customDbRun] 自定义执行方法
  static Future<T> customRun<T>(CustomDbRum<T> customDbRun) {
    return customDbRun(_dbManager);
  }

  ///执行sql语句
  ///[sql] sql语句
  ///[arguments] 参数
  ///'CREATE TABLE Test (id INTEGER PRIMARY KEY, name TEXT, value INTEGER, num REAL)');
  Future execute(String sql, [List<Object?>? arguments]) async {
    return _dbManager.execute(sql, arguments);
  }

  ///创建表
  ///[entity] 实体
  static Future createTable<T extends CacheSqlLiteBaseEntity>(String tableSql) {
    LogUtil.debug("sqlLite: createTable $tableSql");
    return _dbManager.execute(tableSql);
  }

  ///添加数据
  ///[entity] 实体
  ///[conflictAlgorithm] 冲突策略
  static Future<int> insert<T extends CacheSqlLiteBaseEntity>(T entity, {ConflictAlgorithm conflictAlgorithm = ConflictAlgorithm.replace}) async {
    Map<String, dynamic> map = entity.toInsertParamsMap();
    try {
      LogUtil.debugFunc(() {
        return "sqlLite: insert ${entity.table()} params: ${JsonUtil.toJson(map)}";
      });
      return _dbManager.insert(entity.table(), map, conflictAlgorithm: conflictAlgorithm);
    } catch (e) {
      return Future.error("添加数据失败");
    }
  }

  ///添加数据
  ///[entitys] 实体
  ///[conflictAlgorithm] 冲突策略
  static Future batchInsert<T extends CacheSqlLiteBaseEntity>(Iterable<T> entitys, {ConflictAlgorithm? conflictAlgorithm}) async {
    if (CollectionUtil.isEmpty(entitys)) {
      return Future(() => 0);
    }
    Map<Type, List<CacheSqlLiteBaseEntity>> mapList = entitys.fold<Map<Type, List<CacheSqlLiteBaseEntity>>>({}, (map, e) {
      List<CacheSqlLiteBaseEntity> list = map[e.runtimeType] ?? [];
      list.add(e);
      map[e.runtimeType] = list;
      return map;
    });
    Iterable<_BatchInsertParams?> iterable =
        mapList.values.map((e) => _buildBatchInsertParams(entitys, conflictAlgorithm: conflictAlgorithm)).where((element) => element != null);

    ///通过事务的方式添加数据
    return _dbManager.transaction((txn) {
      for (_BatchInsertParams? params in iterable) {
        if (params != null) {
          ///执行添加语句
          txn.rawInsert(params.sql, params.paraps);
        }
      }
      return Future.value(null);
    });
  }

  static _BatchInsertParams? _buildBatchInsertParams<T extends CacheSqlLiteBaseEntity>(Iterable<T> entitys, {ConflictAlgorithm? conflictAlgorithm}) {
    if (CollectionUtil.isEmpty(entitys)) {
      return null;
    }
    CacheSqlLiteBaseEntity entity = entitys.first;
    List<Map<String, dynamic?>> mapList = entitys.map((e) => e.toInsertParamsMap()).toList();
    Map<String, dynamic> entityMap = mapList[0];
    List<dynamic> params = [];
    List<String> keys = [];

    ///构建添加语句
    StringBuffer insert = StringBuffer(" insert ");
    if (conflictAlgorithm != null) {
      insert.write(' ${_conflictValues[conflictAlgorithm.index]}');
    }
    insert.write(" into ${entity.table()} ( ");

    ///构建添加的属性
    bool ifFirst = true;
    for (String key in entityMap.keys) {
      keys.add(key);
      if (ifFirst) {
        ifFirst = false;
        insert.write(" $key ");
      } else {
        insert.write(", $key ");
      }
    }
    insert.write(" ) ");
    insert.write(" values ");

    bool ifValueFirst = true;

    for (Map<String, dynamic?> value in mapList) {
      if (ifValueFirst) {
        insert.write(" ( ");
        ifValueFirst = false;
      } else {
        insert.write(", ( ");
      }
      ifFirst = true;
      for (String key in keys) {
        ///构建添加的值
        if (ifFirst) {
          ifFirst = false;
          insert.write(" ? ");
        } else {
          insert.write(", ? ");
        }
        params.add(value[key]);
      }
      insert.write(" ) ");
    }
    String sql = insert.toString();
    LogUtil.debugFunc(() {
      return "sqlLite: $sql params: ${JsonUtil.toJson(params)}";
    });
    return _BatchInsertParams(sql, params);
  }

  ///修改数据
  ///[entity] 实体
  ///[updateParams] 更新参数
  ///[whereParams] 条件
  static Future<int> updateByEntity<T extends CacheSqlLiteBaseEntity>(
    T entity,
    Map<String, dynamic> updateParams, {
    bool igonWhereParamsNull = false,
  }) {
    try {
      _WhereValue where = _WhereValue.buildWhereValue({entity.getIdKey(): entity.getId()}, igonWhereParamsNull);
      LogUtil.debugFunc(() {
        return "sqlLite: update ${entity.table()} params: ${JsonUtil.toJson(updateParams)}  where: ${JsonUtil.toJson(where)}";
      });
      return _dbManager.update(entity.table(), updateParams, where: where.whereSql, whereArgs: where.whereArgs);
    } catch (e) {
      return Future.error("修改数据失败 $e");
    }
  }

  ///修改数据
  ///[entity] 实体
  ///[updateParams] 更新参数
  ///[whereParams] 条件
  static Future<int> update(String table, Map<String, dynamic> updateParams, {Map<String, dynamic>? whereParams, bool igonWhereParamsNull = false}) {
    try {
      _WhereValue where = _WhereValue.buildWhereValue(whereParams, igonWhereParamsNull);
      LogUtil.debugFunc(() {
        return "sqlLite: update ${table} params: ${JsonUtil.toJson(updateParams)}  where: ${JsonUtil.toJson(where)}";
      });
      return _dbManager.update(table, updateParams, where: where.whereSql, whereArgs: where.whereArgs);
    } catch (e) {
      return Future.error("修改数据失败 $e");
    }
  }

  ///删除数据
  ///[entity] 实体
  ///[whereParams] 条件
  static Future<int> delete<T extends CacheSqlLiteBaseEntity>(T entity, Map<String, dynamic>? whereParams, {bool igonWhereParamsNull = false}) {
    try {
      _WhereValue where = _WhereValue.buildWhereValue(whereParams, igonWhereParamsNull);
      LogUtil.debugFunc(() {
        return "sqlLite: delete ${entity.table()} where: ${JsonUtil.toJson(where)}";
      });
      return _dbManager.delete(entity.table(), where: where.whereSql, whereArgs: where.whereArgs);
    } catch (e) {
      return Future.error("删除数据失败");
    }
  }

  ///通过id删除数据
  static Future<int> deleteById<T extends CacheSqlLiteBaseEntity>(T entity) {
    return delete(entity, {entity.getIdKey(): entity.getId()});
  }

  ///查询数据
  ///[entity] 实体
  ///[retParams] 返回参数
  ///[whereParams] 条件
  ///[distinct] 是否去重
  static Future<R?> getById<R>(String table, String id,
      {String idKey = "id",
      List<String>? retParams,
      Map<String, dynamic>? whereParams,
      bool igonWhereParamsNull = false,
      bool distinct = true,
      String? groupBy,
      String? having,
      String? orderBy,
      ResultToEntity<R>? resultToEntity}) {
    return query(table, retParams: retParams, whereParams: {idKey: id}, distinct: distinct, groupBy: groupBy, having: having, orderBy: orderBy)
        .then((value) {
      if (CollectionUtil.isNotEmpty(value)) {
        return resultToEntity != null ? resultToEntity(value[0]) : value[0];
      } else {
        return null;
      }
    });
  }

  ///查询数据
  static Future<List<Map<String, Object?>>?> rawQuery(String sql, {List<Object?>? arguments}) {
    LogUtil.debug("query: $sql arg: ${arguments == null ? {} : JsonUtil.toJson(arguments)}");
    return _dbManager.findBySQL(sql, arguments: arguments);
  }

  ///查询数据
  static Future<List<R>> rawEntityQuery<R>(String sql, ResultToEntity<R> resultToEntity, {List<Object?>? arguments}) {
    return rawQuery(sql, arguments: arguments).then((value) {
      if (CollectionUtil.isEmpty(value)) {
        return [];
      } else {
        return value!.map((e) {
          return resultToEntity(e);
        }).toList();
      }
    });
  }

  ///查询数据
  ///[entity] 实体
  ///[retParams] 返回参数
  ///[whereParams] 条件
  ///[igonWhereParamsNull] 是否忽略where参数为null的参数
  ///[distinct] 是否去重
  static Future<List<R>> entityQuery<R>(String table, ResultToEntity<R> resultToEntity,
      {List<String>? retParams,
      Map<String, dynamic>? whereParams,
      bool igonWhereParamsNull = false,
      bool distinct = true,
      String? groupBy,
      String? having,
      String? orderBy}) {
    return query(table,
            retParams: retParams,
            whereParams: whereParams,
            igonWhereParamsNull: igonWhereParamsNull,
            distinct: distinct,
            groupBy: groupBy,
            having: having,
            orderBy: orderBy)
        .then((value) {
      return value.map((e) {
        return resultToEntity(e);
      }).toList();
    });
  }

  ///查询数据
  ///[entity] 实体
  ///[retParams] 返回参数
  ///[whereParams] 条件
  ///[igonWhereParamsNull] 是否忽略where参数为null的参数
  ///[distinct] 是否去重
  static Future<List> query(String table,
      {List<String>? retParams,
      Map<String, dynamic>? whereParams,
      bool igonWhereParamsNull = false,
      bool distinct = true,
      String? groupBy,
      String? having,
      String? orderBy}) {
    try {
      _WhereValue where = _WhereValue.buildWhereValue(whereParams, igonWhereParamsNull);
      LogUtil.debugFunc(() {
        return "sqlLite: query ${table} params: ${retParams == null ? "all" : JsonUtil.toJson(retParams)}  where: ${JsonUtil.toJson(where)}";
      });
      return _dbManager.findBy(table,
          distinct: distinct,
          columns: retParams,
          where: where.whereSql,
          whereArgs: where.whereArgs,
          groupBy: groupBy,
          having: having,
          orderBy: orderBy);
    } catch (e) {
      return Future.error("查询数据失败 $e");
    }
  }

  ///分页查询数据
  ///[entity] 实体
  ///[pageParam] 分页参数
  ///[retParams] 返回参数
  ///[whereParams] 条件
  ///[distinct] 是否去重
  static Future<PageBean<R>> pageQuery<R>(String table, PageParam pageParam,
      {List<String>? retParams,
      Map<String, dynamic>? whereParams,
      bool igonWhereParamsNull = false,
      bool distinct = true,
      String? groupBy,
      String? having,
      String? orderBy,
      ResultToEntity<R>? resultToEntity}) {
    try {
      _WhereValue where = _WhereValue.buildWhereValue(whereParams, igonWhereParamsNull);
      LogUtil.debugFunc(() {
        return "sqlLite: pageQuery ${table} retPrams: ${retParams == null ? "all" : JsonUtil.toJson(retParams)}  where: ${JsonUtil.toJson(where ?? {})} pageParam: ${JsonUtil.toJson(pageParam)}";
      });
      int offset = (pageParam.pageNum - 1) * pageParam.numPerPage;
      int limit = pageParam.numPerPage;
      return _dbManager
          .findBy(table,
              distinct: distinct,
              columns: retParams,
              where: where.whereSql,
              whereArgs: where.whereArgs,
              limit: limit,
              offset: offset,
              groupBy: groupBy,
              having: having,
              orderBy: orderBy)
          .then((value) {
        dynamic nResult;
        if (resultToEntity != null) {
          nResult = value.map(resultToEntity).toList();
        } else {
          nResult = value;
        }
        return _dbManager
            .countQuery(table, distinct: distinct, where: where.whereSql, whereArgs: where.whereArgs, groupBy: groupBy, having: having)
            .then((count) {
          return PageBean.from(count, nResult, pageParam);
        });
      });
    } catch (e) {
      return Future.error("查询数据失败 $e");
    }
  }

  ///查询数据总数
  ///[entity] 实体
  ///[whereParams] 条件
  ///[distinct] 是否去重
  static Future<int> queryCount(String table, PageParam pageParam,
      {Map<String, dynamic>? whereParams, bool igonWhereParamsNull = false, bool distinct = true, String? groupBy, String? having, String? orderBy}) {
    try {
      _WhereValue where = _WhereValue.buildWhereValue(whereParams, igonWhereParamsNull);
      LogUtil.debugFunc(() {
        return "sqlLite: queryCount ${table} pageParam: ${JsonUtil.toJson(pageParam ?? {})}  where: ${JsonUtil.toJson(where ?? {})}";
      });
      return _dbManager.countQuery(table,
          where: where.whereSql, whereArgs: where.whereArgs, distinct: distinct, groupBy: groupBy, having: having, orderBy: orderBy);
    } catch (e) {
      return Future.error("查询数据失败 $e");
    }
  }

  static final List<String> _conflictValues = <String>['OR ROLLBACK', 'OR ABORT', 'OR FAIL', 'OR IGNORE', 'OR REPLACE'];
}

class _BatchInsertParams {
  String sql;
  List<dynamic> paraps;

  _BatchInsertParams(this.sql, this.paraps);
}

class _WhereValue {
  String? whereSql;
  List<dynamic?>? whereArgs;

  _WhereValue(this.whereSql, this.whereArgs);

  String toJson() {
    return JsonUtil.toJson({"whereSql": whereSql, "whereArgs": whereArgs});
  }

  static _WhereValue buildWhereValue(Map<String, dynamic?>? whereParams, bool igonNullParams) {
    StringBuffer? whereSql;
    List<dynamic>? whereArgs;
    if (CollectionUtil.isNotEmpty(whereParams)) {
      bool isFirst = true;
      whereSql = StringBuffer();
      whereArgs = [];
      for (MapEntry<String, dynamic> entity in whereParams!.entries) {
        String key = entity.key;
        dynamic value = entity.value;
        if (isFirst) {
          isFirst = false;
        } else {
          whereSql.write(" and ");
        }
        if (value is Iterable) {
          ///如果值为list,则代表为in 查询
          _checkValue(value);
          value = value.map((e) {
            if (e is String) {
              return "'$e'";
            } else {
              return e.toString();
            }
          });
          whereSql.write("$key in (${value.join(',')}) ");
        } else {
          if (value == null) {
            ///如果不忽略空条件的话,则该值判断该值为null
            if (!igonNullParams) {
              whereSql.write(" $key IS NULL ");
            }
          } else {
            _checkValue(value);
            whereSql.write("$key=? ");
            whereArgs.add(value);
          }
        }
      }
    }
    return _WhereValue(whereSql?.toString(), whereArgs);
  }

  static void _checkValue(dynamic value) {
    if (value == null) {
      return;
    }
    if (value is String) {
      if (value.contains("}") || value.contains("{") || value.contains("'") || value.contains("\"") || value.contains("(") || value.contains(")")) {
        throw Exception("value不能包含特殊符号及括号 $value");
      }
    }
    if (value is List) {
      value.forEach((element) {
        _checkValue(element);
      });
    }
    if (value is Map) {
      for (MapEntry entry in value.entries) {
        _checkValue(entry.key);
        _checkValue(entry.value);
      }
    }
    return;
  }
}

class DBManager {
  /// 数据库名
  final String _dbName = "db_kittlen_app";

  /// 数据库版本
  final int _version = 1;
  static final DBManager _instance = DBManager._();

  factory DBManager() {
    return _instance;
  }

  DBManager._();

  static Database? _db;

  Future<Database> get db async {
    return _db ??= await _initDB();
  }

  /// 初始化数据库
  Future<Database> _initDB() async {
    Directory directory = await getApplicationDocumentsDirectory();
    String path = join(directory.path, _dbName);
    return await openDatabase(
      path,
      version: _version,
      onCreate: _onCreate,
      onUpgrade: _onUpgrade,
    );
  }

  /// 创建表
  Future _onCreate(Database db, int version) async {}

  /// 更新表
  Future _onUpgrade(Database db, int oldVersion, int newVersion) async {}

  ///事务控制
  //调用样例
  //  try {
  //     await dbUtil.transaction((txn) async {
  //        Map<String,Object> par = Map<String,Object>();
  //        par['uid'] = Random().nextInt(10); par['fuid'] = Random().nextInt(10);
  //        par['type'] = Random().nextInt(2); par['id'] = 1;
  //        var a = await txn.insert('relation', par);
  //        var b = await txn.insert('relation', par);
  //   });
  //   } catch (e) {
  //     print('sql异常:$e');
  //   }
  Future<T> transaction<T>(Future<T> Function(Transaction txn) action, {bool? exclusive}) async {
    Database database = await db;
    return database.transaction(action, exclusive: exclusive);
  }

  ///添加sql数据
  ///[table]表名
  ///[values]数据
  ///    var value = {
  ///    'id':'uuid_short',
  ///      'sex': 1,
  ///      'name': '张三',
  ///    };
  ///    int id = await db.insert(
  ///      'user',
  ///      value,
  ///      conflictAlgorithm: ConflictAlgorithm.replace,
  ///    );
  Future<int> insert(String table, Map<String, Object?> values, {String? nullColumnHack, ConflictAlgorithm? conflictAlgorithm}) async {
    Database database = await db;
    return await database.insert(table, values, nullColumnHack: nullColumnHack, conflictAlgorithm: conflictAlgorithm);
  }

  ///纯sql添加数据
  /// const String sql = """
  /// INSERT INTO User(id,name,sex) values(?,?,?)
  /// """;
  /// arguments = ["张三",1]
  Future rawInsert(String sql, List<Object?>? arguments) async {
    Database database = await db;
    return await database.rawInsert(sql, arguments);
  }

  /// 查询全部数据
  Future<List<Map<String, Object?>>> findAll(String table) async {
    Database? database = await db;
    return database.query(table);
  }

  /// 根据条件查询全部数据
  /// [table]表名
  /// [columns] 显示的列
  /// [distinct] 去重查询
  /// [where]条件
  /// [whereArgs]条件参数
  /// [groupBy]分组
  /// [having]过滤
  /// [orderBy]排序
  /// [limit] 限制条数
  /// [offset] 跳过条数
  ///  List<Map> maps = await db.query(user,
  ///      columns: ['id', 'name'],
  ///      where: 'name = ?',
  ///      whereArgs: ["张三"]);
  Future<List<Map<String, Object?>>> findBy(String table,
      {bool? distinct,
      List<String>? columns,
      String? where,
      List<Object?>? whereArgs,
      String? groupBy,
      String? having,
      String? orderBy,
      int? limit,
      int? offset}) async {
    Database? database = await db;
    return database.query(table,
        distinct: distinct,
        columns: columns,
        where: where,
        whereArgs: whereArgs,
        groupBy: groupBy,
        having: having,
        orderBy: orderBy,
        limit: limit,
        offset: offset);
  }

  ///查询条数
  Future<int> countQuery(String table, {bool? distinct, String? where, List<Object?>? whereArgs, String? groupBy, String? having, String? orderBy}) {
    checkWhereArgs(whereArgs);
    final query = StringBuffer();
    query.write("select ");
    if (distinct == true) {
      query.write(' DISTINCT ');
    }
    query.write(" count(*) as c from ");
    query.write(table);
    _writeClause(query, ' WHERE ', where);
    _writeClause(query, ' GROUP BY ', groupBy);
    _writeClause(query, ' HAVING ', having);
    _writeClause(query, ' ORDER BY ', orderBy);
    List<Object?>? arguments = whereArgs != null ? List<Object?>.from(whereArgs) : null;
    return findBySQL(query.toString(), arguments: arguments).then((value) {
      if (CollectionUtil.isEmpty(value)) {
        return 0;
      }
      return MapUtil.mapGetOrDef(value!.first, "c", 0);
    });
  }

  /// 根据sql查询数据
  /// [sql] sql语句
  /// [arguments] 参数
  Future<List<Map<String, Object?>>?> findBySQL(String sql, {List<Object?>? arguments}) async {
    Database? database = await db;
    return database.rawQuery(sql, arguments);
  }

  /// 更新数据
  /// [table]表名
  /// [values]数据
  /// [where]条件
  /// [whereArgs]条件参数
  /// int count = await db.update(user, ["set":1]),
  ///    where: 'name = ?', whereArgs: ['张三']);
  Future<int> update(String table, Map<String, Object?> values,
      {String? where, List<Object?>? whereArgs, ConflictAlgorithm? conflictAlgorithm}) async {
    Database? database = await db;
    return database.update(table, values, where: where, whereArgs: whereArgs, conflictAlgorithm: conflictAlgorithm);
  }

  /// 纯sql更新数据
  /// const String sql = """
  /// UPDATE User set name = ?, sex = ? where id = ?
  /// """;
  /// arguments = ["张三",1,1]
  Future<int> rawUpdate(String sql, [List<Object?>? arguments]) async {
    Database? database = await db;
    return database.rawUpdate(sql, arguments);
  }

  /// 删除数据
  /// [table]表名
  /// [where]条件
  /// [whereArgs]条件参数
  ///int count = await db.delete(user, where: 'id = ?', whereArgs: ["id"]);
  Future<int> delete(String table, {String? where, List<Object?>? whereArgs}) async {
    Database? database = await db;
    return database.delete(table, where: where, whereArgs: whereArgs);
  }

  ///纯sql删除数据
  ///   .rawDelete('DELETE FROM user WHERE id = ?', ['id']);
  Future<int> rawDelete(String sql, [List<Object?>? arguments]) async {
    Database? database = await db;
    return database.rawDelete(sql, arguments);
  }

  ///执行sql语句
  ///[sql] sql语句
  ///[arguments] 参数
  ///'CREATE TABLE Test (id INTEGER PRIMARY KEY, name TEXT, value INTEGER, num REAL)');
  Future execute(String sql, [List<Object?>? arguments]) async {
    Database? database = await db;
    return database.execute(sql, arguments);
  }

  void _writeClause(StringBuffer s, String name, String? clause) {
    if (clause != null) {
      s.write(name);
      s.write(clause);
    }
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值