SQLite(Kotlin 多平台)

androidx.sqlite 库包含抽象接口以及基本的 可以用来构建自己的库 SQLite。您可以考虑使用 Room 库,它提供了 在 SQLite 上创建一个抽象层, 充分利用 SQLite 的强大功能。

设置依赖项

androidx.sqlite 的当前版本(支持 Kotlin 多平台) (KMP) 为 2.5.0-alpha01 或更高版本。

如需在 KMP 项目中设置 SQLite,请添加制品的依赖项 在您的模块的 build.gradle.kts 文件中添加以下代码:

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

SQLite 驱动程序 API

androidx.sqlite 库组提供用于 使用 androidx.sqlite:sqlite-bundled 或托管平台(例如 Android 或 iOS)中 使用 androidx.sqlite:sqlite-framework 时。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: <ph type="x-smartling-placeholder">
      </ph>
    • 选择性地使用 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(桌面)

推荐使用的实现是:BundledSQLiteDriver,位于 androidx.sqlite:sqlite-bundled。它包含从该文件编译的 SQLite 库。 提供最新的版本,并在所有 Google Cloud 项目 支持的 KMP 平台

SQLite 驱动程序和 Room

驱动程序 API 有助于与 SQLite 数据库进行低级交互。 如需一个功能丰富的库,以便提供更可靠的 SQLite 访问,则 建议使用 Room。

RoomDatabase 依赖 SQLiteDriver 执行数据库操作以及 需要使用 RoomDatabase.Builder.setDriver()。客房提供 RoomDatabase.useReaderConnectionRoomDatabase.useWriterConnection:更直接地访问 数据库连接。