androidx.sqlite
程式庫包含抽象介面和基本實作,可用來建構自己的資料庫來存取 SQLite。建議您考慮使用 Room 程式庫,原因在於該程式庫透過 SQLite 提供抽象層,可提升資料庫存取的穩固性,並同時充分利用 SQLite 的強大功能。
設定依附元件
如要在 KMP 專案中設定 SQLite,請在模組的 build.gradle.kts
檔案中新增構件的依附元件:
[versions]
sqlite = "2.5.2"
[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
時會納入程式庫,使用 androidx.sqlite:sqlite-framework
時則會納入主機平台,例如 Android 或 iOS)。這些 API 密切遵循 SQLite C API 的核心功能。
主要有 3 個介面:
SQLiteDriver
- 這是使用 SQLite 的進入點,負責開啟資料庫連線。SQLiteConnection
-sqlite3
物件的表示法。SQLiteStatement
-sqlite3_stmt
物件的表示法。
以下範例展示了核心 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.useReaderConnection
和
RoomDatabase.useWriterConnection
,可更直接存取受管理資料庫連線。
遷移至 Kotlin Multiplatform
任何低階 SQLite 呼叫的使用情形,都必須遷移至對應的 SQLite 驅動程式。
Kotlin Multiplatform
使用低階 SQLiteConnection
執行交易
val connection: SQLiteConnection = ...
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 = ...
connection.execSQL("ALTER TABLE ...")
執行查詢,但沒有引數
val connection: SQLiteConnection = ...
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 (cusor.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
}
}