繁体   English   中英

Flutter sqflite打开现有数据库

[英]Flutter sqflite open existing database

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

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

打开资产数据库》指南介绍了在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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM