首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用迁移策略开放资产数据库

使用迁移策略开放资产数据库
EN

Stack Overflow用户
提问于 2019-08-23 15:21:14
回答 1查看 72关注 0票数 1

我按照本指南打开了一个资产数据库,并将其复制到我的文件系统中,但使用了"readOnly:Opening an asset database“,因为我希望用户在应用程序中修改数据库。

代码语言:javascript
复制
  initDB() async {
    Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentsDirectory.path, "TEST.db");

    var exists = await databaseExists(path);

    if (!exists) {
      // Should happen only the first time you launch your application
      print("Creating new copy from asset");

      // Make sure the parent directory exists
      try {
        await Directory(dirname(path)).create(recursive: true);
      } catch (_) {}

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

      // Write and flush the bytes written
      await File(path).writeAsBytes(bytes, flush: true);
    } else {
      print("Opening existing database");
    }
    // open the database
    return await openDatabase(path, version: 1, onUpgrade: _onUpgrade);
  }

这个很好用。

但稍后我想修改资产数据库,例如添加新的行、列或表,甚至更改已存在的特定列的值。当我这样做时,我想用修改后的资产数据库更新文件系统中复制的数据库。为此,我使用onUpgrade。

代码语言:javascript
复制
  _onUpgrade(Database db, int oldVersion, int newVersion) async {
    Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentsDirectory.path, "TEST.db");

    // Delete old database and load new asset database
    await deleteDatabase(path);
    try {
      await Directory(dirname(path)).create(recursive: true);
    } catch (_) {}

    ByteData data = await rootBundle.load(join("assets", "test.db"));
    List<int> bytes =
        data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
    await new File(path).writeAsBytes(bytes, flush: true);

    // Add new table

    // Add new row or column

    // Update column
  }

我只知道如何在版本更改后删除文件系统中的数据库,但我不想删除用户在数据库中所做的更改。如何将新资产数据库与文件系统中的数据库合并?如何添加新的表、列或行?那么如何替换列呢?

EN

回答 1

Stack Overflow用户

发布于 2020-04-08 00:55:49

您必须使用readOnly = false打开它。

然后,当您调用onUpgrade时,您必须运行sql查询来使用alter TABLE命令更改表。

代码语言:javascript
复制
final Future<Database> database = openDatabase(
  // Set the path to the database.
  join(await getDatabasesPath(), 'mydatabase.db'),

  onUpgrade: (db, version ...) {
    return db.execute(
      "ALTER TABLE ... ADD COLUMN ...",
    );
  },
  // Set the version to upgrade
  version: 2,
);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57621539

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档