با مجموعهها، منظم بمانید
ذخیره و طبقهبندی محتوا براساس اولویتهای شما.
کتابخانه androidx.sqlite شامل رابط های انتزاعی به همراه پیاده سازی های اساسی است که می تواند برای ساخت کتابخانه های خود که به SQLite دسترسی دارند استفاده شود. ممکن است بخواهید از کتابخانه Room استفاده کنید، که یک لایه انتزاعی را بر روی SQLite فراهم می کند تا امکان دسترسی قوی تر به پایگاه داده و در عین حال استفاده از قدرت کامل SQLite را فراهم کند.
وابستگی ها را تنظیم کنید
برای راه اندازی SQLite در پروژه KMP خود، وابستگی های مصنوعات را در فایل build.gradle.kts برای ماژول خود اضافه کنید:
[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"}
API های درایور SQLite
گروههای کتابخانه androidx.sqlite APIهای سطح پایینی را برای برقراری ارتباط با کتابخانه SQLite ارائه میدهند که در هنگام استفاده از androidx.sqlite:sqlite-bundled یا در پلتفرم میزبان، مانند Android یا iOS هنگام استفاده از androidx.sqlite:sqlite-framework در کتابخانه گنجانده شده است. 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()}
مشابه API های SQLite C، استفاده رایج این است:
یک اتصال پایگاه داده را با استفاده از پیاده سازی SQLiteDriver نمونه باز کنید.
یک دستور SQL را با استفاده از SQLiteConnection.prepare() آماده کنید.
یک SQLiteStatement به روش زیر اجرا کنید:
به صورت اختیاری آرگومان ها را با استفاده از توابع bind*() پیوند دهید.
با استفاده از تابع step() روی مجموعه نتیجه تکرار کنید.
با استفاده از توابع get*() ستون ها را از مجموعه نتیجه بخوانید.
پیاده سازی درایور
جدول زیر پیاده سازی درایورهای موجود را خلاصه می کند:
نام کلاس
مصنوع
پلتفرم های پشتیبانی شده
AndroidSQLiteDriver
androidx.sqlite:sqlite-framework
اندروید
NativeSQLiteDriver
androidx.sqlite:sqlite-framework
iOS، Mac و Linux
BundledSQLiteDriver
androidx.sqlite:sqlite-bundled
Android، iOS، Mac، Linux و JVM (Desktop)
پیاده سازی توصیه شده برای استفاده BundledSQLiteDriver است که در androidx.sqlite:sqlite-bundled موجود است. این شامل کتابخانه SQLite است که از منبع کامپایل شده است و به روزترین نسخه و سازگاری را در تمام پلتفرم های KMP پشتیبانی شده ارائه می دهد.
درایور و اتاق SQLite
APIهای درایور برای تعاملات سطح پایین با پایگاه داده SQLite مفید هستند. برای یک کتابخانه غنی از ویژگی که دسترسی قوی تری به SQLite فراهم می کند، اتاق توصیه می شود.
یک پرس و جو را با نتیجه اما بدون آرگومان اجرا کنید
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}}
فقط اندروید
تراکنش را با استفاده از 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 و/یا وابستههای آن هستند.
تاریخ آخرین بهروزرسانی 2025-08-13 بهوقت ساعت هماهنگ جهانی.
[[["درک آسان","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-13 بهوقت ساعت هماهنگ جهانی."],[],[],null,["# SQLite (Kotlin Multiplatform)\n\nThe `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-------------------\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------------------\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\n### Driver 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\n### SQLite 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-------------------------------\n\nAny usage of low level SQLite calls need to be migrated to their SQLite Driver\ncounterparts. \n\n### Kotlin 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\n### Android-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 }"]]