kotlin sqlite in
时间: 2023-10-19 20:13:07 浏览: 128
To use SQLite in Kotlin, you need to add the SQLite dependency to your project. You can do this by adding the following code to your app build.gradle file:
```
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.4.21"
implementation 'org.xerial:sqlite-jdbc:3.34.0'
}
```
After adding the dependency, you can start using SQLite in your Kotlin code. Here is an example of how to create a database and a table:
```kotlin
import java.sql.DriverManager
fun main() {
val url = "jdbc:sqlite:test.db"
val connection = DriverManager.getConnection(url)
val statement = connection.createStatement()
statement.execute("""
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER
)
""".trimIndent())
statement.close()
connection.close()
}
```
In this example, we first create a connection to the database using the JDBC driver. Then we create a statement object and execute a SQL command to create a table. Finally, we close the statement and connection objects to release resources.
You can also use SQLite with an ORM (Object-Relational Mapping) library like Room or Exposed to simplify database operations.
阅读全文