SQLite(Kotlin 多平台)

androidx.sqlite 库包含抽象接口和基本实现,可用于构建您自己的访问 SQLite 的库。您可能需要考虑使用 Room 库,它在 SQLite 上提供了一个抽象层,让您能够在充分利用 SQLite 的强大功能的同时,获享更强健的数据库访问机制。

设置依赖项

当前支持 Kotlin 多平台 (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 数据库的低级别交互非常有用。建议使用 Room 作为功能丰富的库来提供更可靠的 SQLite 访问。

RoomDatabase 依靠 SQLiteDriver 执行数据库操作,并且需要使用 RoomDatabase.Builder.setDriver() 配置实现。Room 提供 RoomDatabase.useReaderConnectionRoomDatabase.useWriterConnection,以便更直接访问代管式数据库连接。