Flutter sqflite打开现有数据库 [英] Flutter sqflite open existing database

查看:342
本文介绍了Flutter sqflite打开现有数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can open existing db from assets with flutter and sqflite? I read this guide : https://github.com/tekartik/sqflite/blob/master/doc/opening_db.md#preloading-data

但是我的应用程序显示不是发现表'错误
谢谢。

But my app shows 'not found table' error Thanks.

推荐答案

打开资产数据库指南介绍了在Flutter中捆绑和打开预先存在的SQLite数据库所需执行的步骤app:。

The Opening an asset database guide explains the steps you have to do to bundle and open a pre-existing SQLite database inside your Flutter app:.

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

First, you must edit your pubspec.yaml configuration to refer to your pre-existing SQLite database file, so that it gets bundled into your app when the app is built. In this following example, we will assume the file exists at assets/demo.db under your Flutter app directory:

# 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上作为文件打开。

Next, in your app initialization, you will need to copy the bundled file data into a usable location, because the bundled resource itself can't be directly opened as a file on Android.

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

The sqflite.getDatabasesPath() function will return the directory to use for this. This will typically be something like /data/data/org.example.myapp/databases/ on Android. With this in hand, you can load the byte data from your bundled asset and create the app's writable database file, here named 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);

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

Finally, you can open the created database file on app startup:

var db = await openDatabase(dbPath);

这篇关于Flutter sqflite打开现有数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆