【问题标题】:Flutter sqflite open existing databaseFlutter sqflite 打开现有数据库
【发布时间】:2019-04-07 04:32:01
【问题描述】:

如何使用颤振和 sqflite 从资产中打开现有数据库? 我阅读了本指南: https://github.com/tekartik/sqflite/blob/master/doc/opening_db.md#preloading-data

但我的应用显示“未找到表”错误 谢谢。

【问题讨论】:

    标签: database sqlite flutter


    【解决方案1】:

    Opening an asset database 指南解释了在 Flutter 应用中捆绑和打开预先存在的 SQLite 数据库所必须执行的步骤:。

    首先,您必须编辑您的 pubspec.yaml 配置以引用您预先存在的 SQLite 数据库文件,以便在构建应用程序时将其捆绑到您的应用程序中。在以下示例中,我们将假设该文件存在于您的 Flutter 应用目录下的 assets/demo.db

    # The following section is specific to Flutter.
    flutter:
    
      # The following line ensures that the Material Icons font is
      # included with your application, so that you can use the icons in
      # the material Icons class.
      uses-material-design: true
    
      # To add assets to your application, add an assets section, like this:
      assets:
        - assets/demo.db
    

    接下来,在您的应用初始化中,您需要将捆绑的文件数据复制到可用位置,因为捆绑的资源本身无法在 Android 上直接作为文件打开。

    sqflite.getDatabasesPath() 函数将返回用于此目的的目录。这通常类似于 Android 上的 /data/data/org.example.myapp/databases/。有了这个,您可以从捆绑的资产中加载字节数据并创建应用程序的可写数据库文件,这里命名为app.db

    // Construct the path to the app's writable database file:
    var dbDir = await getDatabasesPath();
    var dbPath = join(dbDir, "app.db");
    
    // Delete any existing database:
    await deleteDatabase(dbPath);
    
    // Create the writable database file from the bundled demo database file:
    ByteData data = await rootBundle.load("assets/demo.db");
    List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
    await File(dbPath).writeAsBytes(bytes);
    

    最后,您可以在应用启动时打开创建的数据库文件:

    var db = await openDatabase(dbPath);
    

    【讨论】:

    • 谢谢。它工作正常,但在更新查询中,我关闭应用程序后的更改被重置!我正在使用本教程创建数据库助手和其他人:grokonez.com/flutter/…@arto-bendiken
    • @david 没有足够的信息进行故障排除。我建议创建另一个问题并更详细地描述您的问题。
    • 这对我也有帮助。我错误地认为 sqflite.getDatabasesPath() 对于资产数据库不是强制性的,可以用实际的数据库文件夹路径替换。
    • @Arto Bendiken 您提供的链接不再有效,是否有更新的链接?我非常需要这个
    • @carlfrank 看起来他们重组了。这是更新的链接:github.com/tekartik/sqflite/blob/master/sqflite/doc/…
    猜你喜欢
    • 1970-01-01
    • 2021-07-09
    • 2021-09-14
    • 2021-10-12
    • 1970-01-01
    • 2023-02-07
    • 2019-12-03
    • 2020-08-19
    • 2019-09-20
    相关资源
    最近更新 更多