在新的应用程序版本中替换数据库

时间:2019-01-16 09:27:03

标签: sqlite dart flutter

我使用现有的数据库文件构建一个应用程序。第一次运行后,将从asstets文件夹复制数据库。我希望能够替换数据库,但前提是数据库已更改。我试图在openDatabase()函数中使用version参数,但是它不起作用。

initDB() async {
    String databasesPath = await getDatabasesPath();
    String path = join(databasesPath, 'db.sqlite');

    Database db;
    try {
      db = await openDatabase(path, readOnly: false);
    } catch (e) {
      print("Error $e");
    }
    if (db == null) {
      // Should happen only the first time you launch your application
      print("Creating new copy from asset");

      // Copy from asset
      ByteData data = await rootBundle.load(join("assets", "db.sqlite"));
      List<int> bytes =
          data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
      await new File(path).writeAsBytes(bytes);

      // open the database
      db = await openDatabase(path, readOnly: false);
    } else {
      print("Opening existing database");
    }
    return db;
}

2 个答案:

答案 0 :(得分:0)

您可以维护数据库属性user_version并检查它何时已更改。要设置它,您将使用PRAGMA user_version = {version};并使用PRAGMA user_version;

查询当前版本

答案 1 :(得分:0)

  

添加onCreate和onUpgrade侦听器。

var theDb = await openDatabase(path,
    version: 14, onCreate: _onCreate, onUpgrade: _onUpgrade);

void _onCreate(Database db, int version) async {
//load your db from assets
print("Created tables");
}
//Drop and create tables onUpgrade or Alter.
FutureOr _onUpgrade(Database db, int oldVersion, int newVersion) {
//code your changes to the db like alter table queries, or drop and create.
}