import 'dart:io'; import 'package:flustars/flustars.dart'; import 'package:path_provider/path_provider.dart'; import 'package:project_telephony/model/send_number_model.dart'; import 'package:sqflite/sqflite.dart'; import 'package:path/path.dart'; class DBManager { /// 数据库名 final String _dbName = "dbName"; /// 数据库版本 final int _version = 1; static final DBManager _instance = DBManager._(); factory DBManager() { return _instance; } DBManager._(); static Database? _db; Future get db async { return _db ??= await _initDB(); } /// 初始化数据库 Future _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 { const String sql = """ CREATE TABLE SendNumber( id INTEGER primary key AUTOINCREMENT, sendNumber TEXT, createdAt datetime ) """; return await db.execute(sql); } /// 更新表 Future _onUpgrade(Database db, int oldVersion, int newVersion) async {} /// 保存数据 Future saveData(SendNumber sendNumber) async { Database database = await db; return await database.insert("SendNumber", sendNumber.toJson()); } /// 使用SQL保存数据 Future saveDataBySQL(SendNumber sendNumber) async { const String sql = """ INSERT INTO SendNumber(sendNumber,createdAt) values(?,?) """; Database database = await db; return await database.rawInsert(sql, [sendNumber.sendNumber, sendNumber.createdAt]); } /// 查询全部数据 Future?> findAll() async { Database? database = await db; List> result = await database.query("SendNumber"); if (result.isNotEmpty) { return result.map((e) => SendNumber.fromJson(e)).toList(); } else { return []; } } ///条件查询 Future?> find(String sendNumber) async { Database database = await db; List> result = await database.query("SendNumber", where: "sendNumber=?", whereArgs: [sendNumber]); if (result.isNotEmpty) { return result.map((e) => SendNumber.fromJson(e)).toList(); } else { return []; } } /// 修改 Future update(SendNumber sendNumber) async { Database database = await db; sendNumber.createdAt = DateUtil.formatDate(DateTime.now()); int count = await database.update("SendNumber", sendNumber.toJson(), where: "sendNumber=?", whereArgs: [sendNumber.sendNumber]); return count; } }