2

我有大量的数据库,我只需要在安装应用程序后创建,这就是我将数据库文件放在资产文件夹中的原因,但我不知道如何使用 SQLDELIGHT 读取它,任何想法?

4

1 回答 1

2

是的,这是可能的。

在创建驱动程序实现之前,在此代码上方:

val driver: SqlDriver = AndroidSqliteDriver (Database.Schema, context, "test.db")

您的预填充数据库必须以指定的名称(此处为“test.db”)放置到 Android 存储数据库的目录中:

// 1. get the database file from the application context obtained in the DatabaseDriverFactory constructor
val database = context.getDatabasePath("test.db")

// 2. check the database file (in first launch the app it does not exist yet)
if (!database.exists()) {
    
    // 3. copy your pre-populated database from resources into the Android database directory
    val inputStream = context.assets.open("dbFileName")
    val outputStream = FileOutputStream(database.absolutePath)
    
    inputStream.use { input: InputStream ->
        outputStream.use { output: FileOutputStream ->
            input.copyTo(output)
        }
    }
}

// 4. create the driver
val driver: SqlDriver = AndroidSqliteDriver(Database.Schema, context, "test.db")

请注意:

  1. 放置在 assets 中的资源可能会被 Android 强行压缩(我没有检查它,因为我的项目在 Kotlin Multiplatform Mobile 上,并且我从共享的 moko-resources 中读取了数据库文件)。其他人建议将资产中的数据库文件名扩展为不可压缩(例如 .pgn)。
  2. 尽管 SQLDelight 不应该每次都按照 .sq 文件中的说明尝试创建数据库,但它会尝试……我踩到了这个耙子。使用 IF NOT EXISTS 指令在 .sq 文件中补充您的 SQL 语句 CREATE(表、索引等)。
于 2021-05-18T13:12:43.240 回答