首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用sqldelight - Android读取assets中的db文件

如何使用sqldelight - Android读取assets中的db文件
EN

Stack Overflow用户
提问于 2020-03-02 05:56:20
回答 1查看 273关注 0票数 1

我有大量的数据库,我只需要创建一旦应用程序是安装的,这就是为什么我把数据库文件放在资产文件夹,但我不确定如何读取它使用SQLDELIGHT,有什么想法吗?

EN

回答 1

Stack Overflow用户

发布于 2021-05-18 21:12:43

是的,这是可能的。

在创建驱动程序实现之前,上面的代码如下:

代码语言:javascript
复制
val driver: SqlDriver = AndroidSqliteDriver (Database.Schema, context, "test.db")

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

代码语言:javascript
复制
// 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. 资源可能会被Android强制压缩(我没有检查它,因为我的项目是在Kotlin多平台移动上的,并且我从共享的moko-
  2. 读取数据库文件)。其他人建议将资产中的数据库文件名扩展为不可压缩(例如,.pgn).
  3. Although SQLDelight不应尝试每次都按照.sq文件中的说明创建数据库,它会尝试...我踩到了这把叉子。补充SQL语句CREATE (表、索引等)在带有IF NOT EXISTS指令的.sq文件中。
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60480150

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档