app_database.dart 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import 'package:sqflite/sqflite.dart';
  2. import 'package:path/path.dart';
  3. import 'package:path_provider/path_provider.dart';
  4. /// 应用数据库管理类
  5. class AppDatabase {
  6. static final AppDatabase _instance = AppDatabase._internal();
  7. static Database? _database;
  8. factory AppDatabase() {
  9. return _instance;
  10. }
  11. AppDatabase._internal();
  12. /// 获取数据库实例
  13. Future<Database> get database async {
  14. if (_database != null) return _database!;
  15. _database = await _initDatabase();
  16. return _database!;
  17. }
  18. /// 初始化数据库
  19. Future<Database> _initDatabase() async {
  20. final documentsDirectory = await getApplicationDocumentsDirectory();
  21. final path = join(documentsDirectory.path, 'sino_med_cloud.db');
  22. return await openDatabase(
  23. path,
  24. version: 1,
  25. onCreate: _onCreate,
  26. onUpgrade: _onUpgrade,
  27. );
  28. }
  29. /// 创建数据库表
  30. Future<void> _onCreate(Database db, int version) async {
  31. // 可以在这里创建表
  32. // 示例:用户表
  33. // await db.execute('''
  34. // CREATE TABLE users (
  35. // id INTEGER PRIMARY KEY AUTOINCREMENT,
  36. // name TEXT NOT NULL,
  37. // email TEXT UNIQUE NOT NULL,
  38. // created_at INTEGER NOT NULL
  39. // )
  40. // ''');
  41. }
  42. /// 升级数据库
  43. Future<void> _onUpgrade(Database db, int oldVersion, int newVersion) async {
  44. // 处理数据库升级逻辑
  45. if (oldVersion < newVersion) {
  46. // 执行升级操作
  47. }
  48. }
  49. /// 关闭数据库
  50. Future<void> close() async {
  51. final db = await database;
  52. await db.close();
  53. _database = null;
  54. }
  55. }