SQLite (Kotlin Multiplatform)

androidx.sqlite 库包含抽象接口和基本实现,可用于构建您自己的访问 SQLite 的库。您可能需要考虑使用 Room 库,它提供了一个 SQLite 之上的抽象层,允许更可靠的数据库访问,同时充分发挥 SQLite 的强大功能。

设置依赖项

当前支持 Kotlin Multi-Platform (KMP) 的 androidx.sqlite 版本是 2.5.0-alpha01 或更高版本。

要在 KMP 项目中设置 SQLite,请在模块的 build.gradle.kts 文件中添加工件的依赖项

  • androidx.sqlite:sqlite - SQLite 驱动程序接口
  • androidx.sqlite:sqlite-bundled - 捆绑驱动程序实现

SQLite 驱动程序 API

androidx.sqlite 库组提供了用于与 SQLite 库通信的低级 API,该库在使用 androidx.sqlite:sqlite-bundled 时包含在库中,或在使用 androidx.sqlite:sqlite-framework 时包含在主机平台(例如 Android 或 iOS)中。这些 API 紧密遵循 SQLite C API 的核心功能。

有 3 个主要接口

以下示例展示了核心 API

fun main() {
  val databaseConnection = BundledSQLiteDriver().open("todos.db")
  databaseConnection.execSQL(
    "CREATE TABLE IF NOT EXISTS Todo (id INTEGER PRIMARY KEY, content TEXT)"
  )
  databaseConnection.prepare(
    "INSERT OR IGNORE INTO Todo (id, content) VALUES (? ,?)"
  ).use { stmt ->
    stmt.bindInt(index = 1, value = 1)
    stmt.bindText(index = 2, value = "Try Room in the KMP project.")
    stmt.step()
  }
  databaseConnection.prepare("SELECT content FROM Todo").use { stmt ->
    while (stmt.step()) {
      println("Action item: ${stmt.getText(0)}")
    }
  }
  databaseConnection.close()
}

与 SQLite C API 类似,常见用法是

  • 使用实例化的 SQLiteDriver 实现打开数据库连接。
  • 使用 SQLiteConnection.prepare() 准备 SQL 语句
  • 通过以下方式执行 SQLiteStatement
    • (可选)使用 bind*() 函数绑定参数。
    • 使用 step() 函数迭代结果集。
    • 使用 get*() 函数从结果集中读取列。

驱动程序实现

下表总结了可用的驱动程序实现

类名

工件

支持的平台

AndroidSQLiteDriver androidx.sqlite:sqlite-framework

Android

NativeSQLiteDriver androidx.sqlite:sqlite-framework

iOS、Mac 和 Linux

BundledSQLiteDriver androidx.sqlite:sqlite-bundled

Android、iOS、Mac、Linux 和 JVM (桌面)

推荐使用的实现是 androidx.sqlite:sqlite-bundled 中可用的 BundledSQLiteDriver。它包含从源代码编译的 SQLite 库,提供了最新版本并在所有受支持的 KMP 平台上保持一致性。

SQLite 驱动程序和 Room

驱动程序 API 对于与 SQLite 数据库进行低级交互非常有用。对于提供更强大 SQLite 访问功能丰富的库,建议使用 Room。

RoomDatabase 依赖于 SQLiteDriver 来执行数据库操作,并且需要使用 RoomDatabase.Builder.setDriver() 配置其实现。Room 提供了 RoomDatabase.useReaderConnectionRoomDatabase.useWriterConnection,以便更直接地访问托管的数据库连接。