sql_manager.dart 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import 'package:flutter/material.dart';
  2. import 'package:path/path.dart';
  3. import 'package:sqflite/sqflite.dart';
  4. class SqlManager {
  5. static const _VERSION = 1;
  6. static const _NAME = "bby.db";
  7. static Database _database;
  8. //初始化
  9. static init() async {
  10. var databasesPath = await getDatabasesPath();
  11. String path = join(databasesPath, _NAME);
  12. _database = await openDatabase(path,
  13. version: _VERSION, onCreate: (Database db, int version) async {});
  14. }
  15. //判断表是否存在
  16. static isTableExits(String tableName) async {
  17. await getCurrentDatabase();
  18. var res = await _database.rawQuery(
  19. "select * from Sqlite_master where type = 'table' and name = '$tableName'");
  20. return res != null && res.length > 0;
  21. }
  22. //查询表
  23. static allTables() async {
  24. await getCurrentDatabase();
  25. var res = await _database.rawQuery(
  26. "select * from Sqlite_master where type = 'table'");
  27. return res;
  28. }
  29. //获取当前数据库对象
  30. static Future<Database> getCurrentDatabase() async {
  31. if (_database == null) {
  32. await init();
  33. }
  34. return _database;
  35. }
  36. //关闭
  37. static close() {
  38. _database?.close();
  39. _database = null;
  40. }
  41. }
  42. abstract class BaseDbProvider {
  43. bool isTableExits = false;
  44. createTableString();
  45. tableName();
  46. //创建表sql语句
  47. tableBaseString(String sql) {
  48. return sql;
  49. }
  50. Future<Database> getDataBase() async {
  51. return await open();
  52. }
  53. //super 函数对父类进行初始化
  54. @mustCallSuper
  55. prepare(name, String createSql) async {
  56. isTableExits = await SqlManager.isTableExits(name);
  57. if (!isTableExits) {
  58. Database db = await SqlManager.getCurrentDatabase();
  59. var e = await db.execute(createSql);
  60. return e;
  61. }
  62. }
  63. @mustCallSuper
  64. open() async {
  65. if (!isTableExits) {
  66. await prepare(tableName(), createTableString());
  67. }
  68. return await SqlManager.getCurrentDatabase();
  69. }
  70. }