SQLite
suggest changeSQLite is a self-contained, serverless, zero-configuration SQL database engine. In Kotlin, it is widely utilized for local storage in Android applications (via Room or SQLDelight), desktop applications (Compose for Desktop), CLI tools, embedded devices, and lightweight backend services via JDBC or JetBrains Exposed.
Setting Up Dependencies
To connect to SQLite on the JVM, use the official sqlite-jdbc driver:
// build.gradle.kts
dependencies {
implementation("org.xerial:sqlite-jdbc:3.53.4.0")
// Optional: JetBrains Exposed SQL library
val exposedVersion = "1.6.0"
implementation("org.jetbrains.exposed:exposed-core:$exposedVersion")
implementation("org.jetbrains.exposed:exposed-jdbc:$exposedVersion")
}
Direct JDBC with SQLite
Connecting and Initializing the Database
SQLite supports persistent disk files as well as fast in-memory databases (jdbc:sqlite::memory:):
import java.sql.Connection
import java.sql.DriverManager
import java.sql.ResultSet
data class Task(val id: Int, val title: String, val completed: Boolean)
class TaskDatabase(dbPath: String = "tasks.db") {
private val url = "jdbc:sqlite:$dbPath"
private fun connect(): Connection {
val conn = DriverManager.getConnection(url)
// Enable WAL mode and foreign key constraints
conn.createStatement().use { stmt ->
stmt.execute("PRAGMA journal_mode = WAL;")
stmt.execute("PRAGMA foreign_keys = ON;")
}
return conn
}
init {
connect().use { conn ->
conn.createStatement().use { stmt ->
stmt.execute(
"""
CREATE TABLE IF NOT EXISTS tasks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
completed INTEGER NOT NULL DEFAULT 0
);
""".trimIndent()
)
}
}
}
fun addTask(title: String): Int {
val sql = "INSERT INTO tasks (title, completed) VALUES (?, ?)"
return connect().use { conn ->
conn.prepareStatement(sql, java.sql.Statement.RETURN_GENERATED_KEYS).use { stmt ->
stmt.setString(1, title)
stmt.setInt(2, 0)
stmt.executeUpdate()
stmt.generatedKeys.use { rs ->
if (rs.next()) rs.getInt(1) else -1
}
}
}
}
fun getAllTasks(): List<Task> {
val sql = "SELECT id, title, completed FROM tasks ORDER BY id ASC"
return connect().use { conn ->
conn.prepareStatement(sql).use { stmt ->
stmt.executeQuery().use { rs ->
val list = mutableListOf<Task>()
while (rs.next()) {
list.add(
Task(
id = rs.getInt("id"),
title = rs.getString("title"),
completed = rs.getInt("completed") == 1
)
)
}
list
}
}
}
}
fun markCompleted(id: Int) {
val sql = "UPDATE tasks SET completed = 1 WHERE id = ?"
connect().use { conn ->
conn.prepareStatement(sql).use { stmt ->
stmt.setInt(1, id)
stmt.executeUpdate()
}
}
}
}
Usage
fun main() {
val db = TaskDatabase("todo.db")
val id1 = db.addTask("Write documentation")
val id2 = db.addTask("Run test suite")
println("Created tasks: $id1, $id2")
db.markCompleted(id1)
val all = db.getAllTasks()
for (t in all) {
val status = if (t.completed) "[X]" else "[ ]"
println("${t.id}. $status ${t.title}")
}
}
Transactions and Rollbacks
SQLite operations are atomic. Multiple operations can be grouped into an explicit transaction to ensure consistency:
fun transferCredits(conn: Connection, fromUser: Int, toUser: Int, amount: Int) {
val prevAutoCommit = conn.autoCommit
try {
conn.autoCommit = false // Begin transaction
conn.prepareStatement("UPDATE accounts SET balance = balance - ? WHERE id = ?").use { stmt ->
stmt.setInt(1, amount)
stmt.setInt(2, fromUser)
stmt.executeUpdate()
}
conn.prepareStatement("UPDATE accounts SET balance = balance + ? WHERE id = ?").use { stmt ->
stmt.setInt(1, amount)
stmt.setInt(2, toUser)
stmt.executeUpdate()
}
conn.commit() // Commit both updates
println("Transfer committed successfully.")
} catch (e: Exception) {
conn.rollback() // Rollback on any failure
println("Transfer failed and rolled back: ${e.message}")
throw e
} finally {
conn.autoCommit = prevAutoCommit
}
}
Using SQLite with JetBrains Exposed
JetBrains Exposed provides an idiomatic, type-safe DSL over SQLite:
import org.jetbrains.exposed.v1.core.*
import org.jetbrains.exposed.v1.jdbc.*
import org.jetbrains.exposed.v1.jdbc.transactions.transaction
object Products : Table("products") {
val id = integer("id").autoIncrement()
val name = varchar("name", 100)
val price = double("price")
override val primaryKey = PrimaryKey(id)
}
fun main() {
// In-memory SQLite database
Database.connect("jdbc:sqlite:file:test?mode=memory&cache=shared", "org.sqlite.JDBC")
transaction {
SchemaUtils.create(Products)
// Insert
val prodId = Products.insert {
it[name] = "Mechanical Keyboard"
it[price] = 89.99
} get Products.id
// Query
val items = Products.selectAll().where { Products.price greaterEq 50.0 }.map {
"${it[Products.name]} costs \$${it[Products.price]}"
}
println("Found: $items")
}
}
Best Practices
- Enable WAL Mode: Execute
PRAGMA journal_mode = WAL;. Write-Ahead Logging allows readers to read concurrently while a writer is writing, preventingdatabase is lockederrors. - Enable Foreign Keys Explicitly: By default, SQLite disables foreign key validation for backward compatibility. Always execute
PRAGMA foreign_keys = ON;. - Always use parameterized queries (
PreparedStatement): Prevents SQL injection and lets SQLite reuse compiled query bytecode. - Use in-memory mode for unit tests: Running tests against
jdbc:sqlite::memory:is instantaneous and requires no filesystem cleanup.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents