為 KMP 設定 SQLite

androidx.sqlite 程式庫包含抽象介面和基本實作,可用來建構您自己的程式庫,以便存取 SQLite。建議您考慮使用 Room 程式庫,原因在於該程式庫透過 SQLite 提供抽象層,可提升資料庫存取的穩固性,並同時充分利用 SQLite 的強大功能。

設定依附元件

如要在 KMP 專案中設定 SQLite,請在模組的 build.gradle.kts 檔案中新增構件的依附元件:

[versions]
sqlite = "2.7.1"

[libraries]
# The SQLite Driver interfaces
androidx-sqlite = { module = "androidx.sqlite:sqlite", version.ref = "sqlite" }

# The bundled SQLite driver implementation
androidx-sqlite-bundled = { module = "androidx.sqlite:sqlite-bundled", version.ref = "sqlite" }

[plugins]
ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" }

SQLite 驅動程式 API

androidx.sqlite 程式庫群組提供低階 API,可與 SQLite 程式庫通訊。使用 androidx.sqlite:sqlite-bundled 時,SQLite 程式庫會包含在程式庫中;使用 androidx.sqlite:sqlite-framework 時,SQLite 程式庫則包含在主機平台 (例如 Android 或 iOS) 中。這些 API 緊密遵循 SQLite C API 的核心功能。

主要介面有三個:

以下範例展示了核心 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 類似,常見的使用模式包含下列步驟:

  1. 使用例項化的 SQLiteDriver 實作開啟資料庫連線。
  2. 使用 SQLiteConnection.prepare 準備 SQL 陳述式。
  3. 請按照下列步驟執行 SQLiteStatement:
    1. 選用:使用 bind* 函式繫結引數。
    2. 使用 step 函式疊代結果集。
    3. 使用 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 (電腦)

WebWorkerSQLiteDriver androidx.sqlite:sqlite-web

JavaScript 和 WebAssembly (WasmJS)

建議使用 androidx.sqlite:sqlite-bundled 中的 BundledSQLiteDriver。其中包含從來源編譯的 SQLite 程式庫,提供最新版本,並在所有支援的 KMP 平台保持一致。

SQLite 驅動程式和 Room

驅動程式 API 適用於與 SQLite 資料庫進行低階互動。如需功能豐富的程式庫,以便更穩定地存取 SQLite,建議使用 Room。

RoomDatabase 依賴 SQLiteDriver 執行資料庫作業,您必須使用 RoomDatabase.Builder.setDriver 設定實作。Room 提供 RoomDatabase.useReaderConnection 和 RoomDatabase.useWriterConnection,可更直接存取受管理的資料庫連線。

遷移至 Kotlin Multiplatform

您必須將所有低階支援 SQLite API 元件 (例如 SupportSQLiteDatabase 介面) 遷移至對等的 SQLite 驅動程式元件。

Kotlin Multiplatform

使用低階 SQLiteConnection 執行交易

val connection: SQLiteConnection = BundledSQLiteDriver().open("todos.db")
connection.execSQL("BEGIN IMMEDIATE TRANSACTION")
try {
    // perform database operations in transaction.
    connection.execSQL("END TRANSACTION")
} catch (t: Throwable) {
    connection.execSQL("ROLLBACK TRANSACTION")
}

執行查詢,但沒有結果

val connection: SQLiteConnection = BundledSQLiteDriver().open("todos.db")
connection.execSQL("ALTER TABLE ...")

執行有結果但沒有引數的查詢

val connection: SQLiteConnection = BundledSQLiteDriver().open("todos.db")
connection.prepare("SELECT * FROM Pet").use { statement ->
    while (statement.step()) {
        // read columns.
        statement.getInt(0)
        statement.getText(1)
    }
}

執行查詢並傳回結果和引數

connection.prepare("SELECT * FROM Pet WHERE id = ?").use { statement ->
    statement.bindInt(1, id)
    if (statement.step()) {
        // row found, read columns.
    } else {
        // row not found.
    }
}

僅限 Android

使用 SupportSQLiteDatabase 執行交易

val database: SupportSQLiteDatabase = ...
database.beginTransaction()
try {
  // perform database operations in transaction
  database.setTransactionSuccessful()
} finally {
  database.endTransaction()
}

執行查詢,但沒有結果

val database: SupportSQLiteDatabase = ...
database.execSQL("ALTER TABLE ...")

執行有結果但沒有引數的查詢

val database: SupportSQLiteDatabase = ...
database.query("SELECT * FROM Pet").use { cursor ->
  while (cursor.moveToNext()) {
    // read columns
    cursor.getInt(0)
    cursor.getString(1)
  }
}

執行查詢並傳回結果和引數

database.query("SELECT * FROM Pet WHERE id = ?", id).use { cursor ->
  if (cursor.moveToNext()) {
    // row found, read columns
  } else {
    // row not found
  }
}