SQLite (Kotlin Multiplatform)

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-bundled 時,或在主機平台 (例如 Android 或 iOS) 中使用 androidx.sqlite:sqlite-framework 時,androidx.sqlite 程式庫群組提供低階 API,可用來與程式庫中的 SQLite 程式庫通訊。這些 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,以便更直接存取代管資料庫連線。