androidx.sqlite 라이브러리에는 SQLite에 액세스하는 자체 라이브러리를 빌드하는 데 사용할 수 있는 기본 구현과 함께 추상 인터페이스가 포함되어 있습니다. SQLite를 완벽히 활용하면서 강력한 데이터베이스 액세스를 지원하는 SQLite의 추상화 레이어를 제공하는 Room 라이브러리 사용을 고려할 수 있습니다.
[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 사용 시 라이브러리에 포함되거나 androidx.sqlite:sqlite-framework 사용 시 Android 또는 iOS와 같은 호스트 플랫폼에 포함된 SQLite 라이브러리와 통신하기 위한 하위 수준 API를 제공합니다. API는 SQLite C API의 핵심 기능을 긴밀하게 따릅니다.
다음과 같은 3가지 주요 인터페이스가 있습니다.
SQLiteDriver - SQLite를 사용하는 진입점이며 데이터베이스 연결을 여는 역할을 합니다.
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()}
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을 사용하는 것이 좋습니다.
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()}
valdatabase:SupportSQLiteDatabase=...database.query("SELECT * FROM Pet").use{cursor->
while(cusor.moveToNext()){// read columnscursor.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}}
이 페이지에 나와 있는 콘텐츠와 코드 샘플에는 콘텐츠 라이선스에서 설명하는 라이선스가 적용됩니다. 자바 및 OpenJDK는 Oracle 및 Oracle 계열사의 상표 또는 등록 상표입니다.
최종 업데이트: 2025-08-27(UTC)
[[["이해하기 쉬움","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 }"]]