[versions]sqlite="2.5.2"[libraries]# The SQLite Driver interfacesandroidx-sqlite={module="androidx.sqlite:sqlite",version.ref="sqlite"}# The bundled SQLite driver implementationandroidx-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 的核心功能。
funmain(){valdatabaseConnection=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()}
valconnection:SQLiteConnection=...connection.prepare("SELECT * FROM Pet").use{statement->
while(statement.step()){// read columnsstatement.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 進行交易
valdatabase:SupportSQLiteDatabase=...database.beginTransaction()try{// perform database operations in transactiondatabase.setTransactionSuccessful()}finally{database.endTransaction()}
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["缺少我需要的資訊","missingTheInformationINeed","thumb-down"],["過於複雜/步驟過多","tooComplicatedTooManySteps","thumb-down"],["過時","outOfDate","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["示例/程式碼問題","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-08-27 (世界標準時間)。"],[],[],null,["The `androidx.sqlite` library contains abstract interfaces along with basic\nimplementations which can be used to build your own libraries that access\nSQLite. You might want to consider using the [Room](/kotlin/multiplatform/room) library, which provides\nan abstraction layer over SQLite to allow for more robust database access while\nharnessing the full power of SQLite.\n\nSet up dependencies\n\nTo setup SQLite in your KMP project, add the dependencies for the artifacts in\nthe `build.gradle.kts` file for your module:\n**Note:** `androidx.sqlite` supports KMP in version 2.5.0 or higher. \n\n [versions]\n sqlite = \"2.5.2\"\n\n [libraries]\n # The SQLite Driver interfaces\n androidx-sqlite = { module = \"androidx.sqlite:sqlite\", version.ref = \"sqlite\" }\n\n # The bundled SQLite driver implementation\n androidx-sqlite-bundled = { module = \"androidx.sqlite:sqlite-bundled\", version.ref = \"sqlite\" }\n\n [plugins]\n ksp = { id = \"com.google.devtools.ksp\", version.ref = \"ksp\" }\n\nSQLite Driver APIs\n\nThe `androidx.sqlite` library groups offer low-level APIs for communicating with\nthe SQLite library either included in the library when using\n`androidx.sqlite:sqlite-bundled` or in the host platform, such as Android or iOS\nwhen using `androidx.sqlite:sqlite-framework`. The APIs closely follow the core\nfunctionality of SQLite C API.\n\nThere are 3 main interfaces:\n\n- [`SQLiteDriver`](/reference/kotlin/androidx/sqlite/SQLiteDriver) - It is the entry point to use SQLite and is responsible for opening database connections.\n- [`SQLiteConnection`](/reference/kotlin/androidx/sqlite/SQLiteConnection) - Is the representation of the `sqlite3` object.\n- [`SQLiteStatement`](/reference/kotlin/androidx/sqlite/SQLiteStatement) - Is the representation of the `sqlite3_stmt` object.\n\nThe following example showcases the core APIs: \n\n fun main() {\n val databaseConnection = BundledSQLiteDriver().open(\"todos.db\")\n databaseConnection.execSQL(\n \"CREATE TABLE IF NOT EXISTS Todo (id INTEGER PRIMARY KEY, content TEXT)\"\n )\n databaseConnection.prepare(\n \"INSERT OR IGNORE INTO Todo (id, content) VALUES (? ,?)\"\n ).use { stmt -\u003e\n stmt.bindInt(index = 1, value = 1)\n stmt.bindText(index = 2, value = \"Try Room in the KMP project.\")\n stmt.step()\n }\n databaseConnection.prepare(\"SELECT content FROM Todo\").use { stmt -\u003e\n while (stmt.step()) {\n println(\"Action item: ${stmt.getText(0)}\")\n }\n }\n databaseConnection.close()\n }\n\nSimilar to SQLite C APIs the common usage is to:\n\n- Open a database connection using the instantiated `SQLiteDriver` implementation.\n- Prepare a SQL statement using `SQLiteConnection.prepare()`\n- Execute a `SQLiteStatement` in the following way:\n 1. Optionally bind arguments using the `bind*()` functions.\n 2. Iterate over the result set using the `step()` function.\n 3. Read columns from the result set using the `get*()` functions.\n\n| **Caution:** Database connections and statements are resources that need to be managed. All prepared statements should be closed once they are no longer needed. Similarly if a database connection is no longer needed, then it should be closed.\n\nDriver Implementations\n\nThe following table summarizes the available driver implementations:\n\n|-----------------------|------------------------------------|--------------------------------------------|\n| Class Name | Artifact | Supported Platforms |\n| `AndroidSQLiteDriver` | `androidx.sqlite:sqlite-framework` | Android |\n| `NativeSQLiteDriver` | `androidx.sqlite:sqlite-framework` | iOS, Mac, and Linux |\n| `BundledSQLiteDriver` | `androidx.sqlite:sqlite-bundled` | Android, iOS, Mac, Linux and JVM (Desktop) |\n\nThe recommended implementation to use is `BundledSQLiteDriver` available in\n`androidx.sqlite:sqlite-bundled`. It includes the SQLite library compiled from\nsource, offering the most up-to-date version and consistency across all the\nsupported KMP platforms.\n\nSQLite Driver and Room\n\nThe driver APIs are useful for low-level interactions with an SQLite database.\nFor a feature rich library that provides a more robust access of SQLite then\nRoom is recommended.\n\nA `RoomDatabase` relies on a `SQLiteDriver` to perform database operations and\nan implementation is required to be configured using\n[`RoomDatabase.Builder.setDriver()`](/reference/kotlin/androidx/room/RoomDatabase#setDriver(androidx.sqlite.SQLiteDriver)). Room provides\n[`RoomDatabase.useReaderConnection`](/reference/kotlin/androidx/room/package-summary#(androidx.room.RoomDatabase).useReaderConnection(kotlin.coroutines.SuspendFunction1)) and\n[`RoomDatabase.useWriterConnection`](/reference/kotlin/androidx/room/package-summary#(androidx.room.RoomDatabase).useWriterConnection(kotlin.coroutines.SuspendFunction1)) for more direct access to the managed\ndatabase connections.\n\nMigrate to Kotlin Multiplatform\n\nAny usage of low level SQLite calls need to be migrated to their SQLite Driver\ncounterparts. \n\nKotlin Multiplatform\n\nPerform a transaction using low-level `SQLiteConnection`\n**Note:** It is always recommended to use `RoomDatabase` transaction APIs as those allow nested transactions and are safer to use than the APIs available in `androidx.sqlite`. \n\n val connection: SQLiteConnection = ...\n connection.execSQL(\"BEGIN IMMEDIATE TRANSACTION\")\n try {\n // perform database operations in transaction\n connection.execSQL(\"END TRANSACTION\")\n } catch(t: Throwable) {\n connection.execSQL(\"ROLLBACK TRANSACTION\")\n }\n\nExecute a query with no result \n\n val connection: SQLiteConnection = ...\n connection.execSQL(\"ALTER TABLE ...\")\n\nExecute a query with result but no arguments \n\n val connection: SQLiteConnection = ...\n connection.prepare(\"SELECT * FROM Pet\").use { statement -\u003e\n while (statement.step()) {\n // read columns\n statement.getInt(0)\n statement.getText(1)\n }\n }\n\nExecute a query with result and arguments \n\n connection.prepare(\"SELECT * FROM Pet WHERE id = ?\").use { statement -\u003e\n statement.bindInt(1, id)\n if (statement.step()) {\n // row found, read columns\n } else {\n // row not found\n }\n }\n\nAndroid-only\n\nPerform a transaction using `SupportSQLiteDatabase`\n**Note:** It is always recommended to use `RoomDatabase` transaction APIs as those allow nested transactions and are safer to use than the APIs available in `androidx.sqlite`. \n\n val database: SupportSQLiteDatabase = ...\n database.beginTransaction()\n try {\n // perform database operations in transaction\n database.setTransactionSuccessful()\n } finally {\n database.endTransaction()\n }\n\nExecute a query with no result \n\n val database: SupportSQLiteDatabase = ...\n database.execSQL(\"ALTER TABLE ...\")\n\nExecute a query with result but no arguments \n\n val database: SupportSQLiteDatabase = ...\n database.query(\"SELECT * FROM Pet\").use { cursor -\u003e\n while (cusor.moveToNext()) {\n // read columns\n cursor.getInt(0)\n cursor.getString(1)\n }\n }\n\nExecute a query with result and arguments \n\n database.query(\"SELECT * FROM Pet WHERE id = ?\", id).use { cursor -\u003e\n if (cursor.moveToNext()) {\n // row found, read columns\n } else {\n // row not found\n }\n }"]]