【问题标题】:Is there a way to check the database version in a flutter app using sqflite?有没有办法使用 sqflite 检查颤振应用程序中的数据库版本?
【发布时间】:2020-06-12 23:20:12
【问题描述】:

我是 Flutter 的新手,我对使用 sqflite 的这些应用程序的数据库版本控制如何工作有一些疑问。

我在我的资产文件夹中创建了一个数据库文件,该文件在启动应用程序时复制到用户的设备上。我想知道是否有任何方法可以检查用户拥有的数据库文件的当前版本,以便不必每次都复制它?

案例: 我对 google play store 中的应用程序更新附带的数据库文件进行了更新。 是否可以检查用户当前拥有的数据库文件的版本以确定是否应该用新文件替换旧文件?

如果是这样...我可以在每次更新我的应用程序时进行此检查吗?每次打开应用程序时我都必须这样做吗?

如果不是......如何最好地处理?处理存储在用户设备上的文件的数据库更新的最佳方法是什么?

【问题讨论】:

    标签: database sqlite flutter updates sqflite


    【解决方案1】:

    SQFlite 已经有一个内置的版本管理,但它只有在你有一个迁移脚本的情况下才能工作。对于你所说的,这可能不是你的情况。您需要手动管理版本控制:

        class DbHelper {
          static const NEW_DB_VERSION = 2;
    
          static final DbHelper _instance = DbHelper.internal();
    
          factory DbHelper() => _instance;
    
          DbHelper.internal();
    
          Database _db;
    
          Future<Database> get db async {
            if (_db != null) {
              return _db;
            } else {
              _db = await initDb();
              return _db;
            }
          }
    
          Future<Database> initDb() async {
    
            final databasesPath = await getDatabasesPath();
            final path = join(databasesPath, "database.db");
    
            var db = await openDatabase(path);
    
            //if database does not exist yet it will return version 0
            if (await db.getVersion() < NEW_DB_VERSION) {
    
              db.close();
    
              //delete the old database so you can copy the new one
              await deleteDatabase(path);
    
              try {
                await Directory(dirname(path)).create(recursive: true);
              } catch (_) {}
    
              //copy db from assets to database folder
              ByteData data = await rootBundle.load("assets/databases/database.db");
              List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
              await File(path).writeAsBytes(bytes, flush: true);
    
              //open the newly created db 
              db = await openDatabase(path);
    
              //set the new version to the copied db so you do not need to do it manually on your bundled database.db
              db.setVersion(NEW_DB_VERSION);
    
            }
    
            return db;
          }
        }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-30
      • 1970-01-01
      • 2019-05-26
      • 2021-09-25
      • 2021-01-16
      • 1970-01-01
      • 1970-01-01
      • 2020-07-05
      相关资源
      最近更新 更多