database - Flutter sqflite 打开现有数据库
问题描述
如何使用颤振和 sqflite 从资产中打开现有数据库?我阅读了本指南: https ://github.com/tekartik/sqflite/blob/master/doc/opening_db.md#preloading-data
但我的应用程序显示“未找到表”错误谢谢。
解决方案
打开资产数据库指南解释了在 Flutter 应用程序中捆绑和打开预先存在的 SQLite 数据库所必须执行的步骤:
首先,您必须编辑pubspec.yaml
配置以引用您预先存在的 SQLite 数据库文件,以便在构建应用程序时将其捆绑到您的应用程序中。在以下示例中,我们将假设该文件存在于assets/demo.db
您的 Flutter 应用目录下:
# 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()
函数将返回用于此的目录。这通常类似于/data/data/org.example.myapp/databases/
在 Android 上。有了这个,您可以从捆绑的资产中加载字节数据并创建应用程序的可写数据库文件,这里命名为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);
推荐阅读
- python - 在 Python 中使用网格方法时出错
- c# - 使用流利的 api 在 ApplicationDbContext 中创建复合键
- heroku - 无法登录 Heroku
- python - 如何在 Pandas 中检查哪些客户同时持有这两种产品
- sql - 如何报告与不同来源的 ID 匹配的测试结果?
- javascript - 设置相同的 dom 元素以插入不同的数据
- reactjs - 'TextField' 未定义 react/jsx-no-undef
- kubernetes - 用于 Ingress 中客户端证书身份验证的 CA 证书轮换
- python - Conda 解决安装 `xeus-cling`
- pytorch - 如何处理 Pytorch Geometric 中未标记的节点?