android - 如何使用 sqldelight 读取位于 Assets 中的数据库文件 - Android

标签 android database kotlin sqldelight

我有大量数据库,只需在安装应用程序后创建,这就是我将数据库文件放置在 Assets 文件夹中的原因,但我不确定如何使用 SQLDELIGHT 从中读取,有什么想法吗?

最佳答案

是的,这是可能的。

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

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. 放置在 asset 中的资源可能会被 Android 强制压缩(我 没有检查它,因为我的项目是在 Kotlin Multiplatform Mobile 上 我从共享的 moko 资源中读取了数据库文件)。其他 人们建议将 Assets 中的数据库文件名扩展为 不可压缩(例如.pgn)。
  2. 虽然 SQLDelight 不应该尝试 每次按照.sq文件中的指令创建数据库, 它尝试...我踩到了这个耙子。补充您的 SQL 语句 在 .sq 文件中使用 IF NOT EXISTS 创建(表、索引等) 说明。

关于android - 如何使用 sqldelight 读取位于 Assets 中的数据库文件 - Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60480150/

相关文章:

java - 保护 Android 应用程序免受网络嗅探

php - 将存储在数据库中的值作为div的高度

database - [H2 and Firebird]auto_increment, identity or trigger plus generator?

php - Codeigniter 数据库无法仅通过一台服务器上的框架进行连接

function - 通用顶级功能引用

lambda - 在 lambda 中使用 return?

java - Android AsyncTask 方法之间的技术差异

android - 如何将 png 格式的图像转换为 Android 的 WSQ 格式

lambda - 范围函数 apply/with/run/also/let : Where do their names come from?

android - 使用 Unicode supportedfont 创建一个应用程序以支持本地语言