[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 ライブラリ グループは、androidx.sqlite:sqlite-bundled を使用する場合はライブラリに含まれる SQLite ライブラリ、androidx.sqlite:sqlite-framework を使用する場合は Android や iOS などのホスト プラットフォームと通信するための低レベル API を提供します。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 UTC。"],[],[],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 }"]]