JDBC from Kotlin
suggest changeJDBC (Java Database Connectivity) is the standard JVM API for talking to relational databases. Every SQL database with a JVM driver (PostgreSQL, MySQL, MariaDB, SQLite, SQL Server, Oracle, H2) speaks JDBC, and higher-level libraries such as Exposed, jOOQ, Spring JDBC and Hibernate are built on top of it.
The API lives in the JDK (java.sql), so from Kotlin you only add the driver for your database. Plain JDBC is verbose in Java, but Kotlin's use, extension functions, lambdas and nullable types make it pleasant enough to use without a framework.
This article covers:
- connecting with
DriverManagerand aDataSource - running statements and parameterized queries
- mapping
ResultSetrows to data classes, includingNULLs - generated keys, batch inserts and transactions
- dates, decimals and other type mappings
- small extension functions that remove the boilerplate
- error handling, connection pooling and coroutines
Database-specific details are in PostgreSQL and SQLite.
Dependencies
The examples use H2, a pure-Java database that runs in memory, so you can run them without installing anything. Only the JDBC URL and the driver dependency change for other databases:
// build.gradle.kts
dependencies {
implementation("com.h2database:h2:2.5.252")
// pick the driver for your real database:
// implementation("org.postgresql:postgresql:42.7.14")
// implementation("com.mysql:mysql-connector-j:26.7.0")
// implementation("org.xerial:sqlite-jdbc:3.53.4.0")
// connection pool (see below)
implementation("com.zaxxer:HikariCP:7.1.0")
}
Drivers register themselves through ServiceLoader, so the old Class.forName("org.h2.Driver") call is not needed.
The main types
| Type | Role |
|---|---|
Connection |
a session with the database; owns transactions |
DriverManager |
creates connections from a JDBC URL |
DataSource |
a connection factory, usually a pool; preferred in applications |
Statement |
executes a fixed SQL string |
PreparedStatement |
executes SQL with ? parameters; use it for anything with input |
ResultSet |
a cursor over query results |
SQLException |
every JDBC error; carries sqlState and errorCode |
Connection, Statement and ResultSet all implement AutoCloseable, so Kotlin's use { } closes them even when an exception is thrown. Leaking them leaks database sessions and cursors, so always close them.
Connecting
A JDBC URL selects the driver and the database:
jdbc:h2:mem:demo;DB_CLOSE_DELAY=-1 H2, in memory, kept until the JVM exits
jdbc:postgresql://localhost:5432/shop PostgreSQL
jdbc:mysql://localhost:3306/shop MySQL
jdbc:sqlite:shop.db SQLite file
import java.sql.Connection
import java.sql.DriverManager
const val URL = "jdbc:h2:mem:demo;DB_CLOSE_DELAY=-1"
fun connect(): Connection = DriverManager.getConnection(URL, "sa", "")
fun main() {
connect().use { conn ->
val meta = conn.metaData
println("${meta.databaseProductName} ${meta.databaseProductVersion}")
println("driver: ${meta.driverName} ${meta.driverVersion}")
println("autoCommit: ${conn.autoCommit}")
}
}
H2 2.5.252 (2026-09-23)
driver: H2 JDBC Driver 2.5.252 (2026-09-23)
autoCommit: true
Don't hard-code real credentials; read them from the environment (see Environment variables) or a configuration file.
A new connection starts in auto-commit mode: every statement is committed as soon as it runs.
Creating tables with Statement
For DDL and other SQL without parameters, a plain Statement is fine. execute runs any SQL, executeUpdate returns the number of affected rows:
fun createSchema(conn: Connection) {
conn.createStatement().use { st ->
st.execute(
"""
CREATE TABLE users (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(200) NOT NULL UNIQUE,
age INT,
balance DECIMAL(12, 2) NOT NULL DEFAULT 0,
created_at TIMESTAMP NOT NULL
)
""".trimIndent()
)
}
}
age is nullable on purpose; it shows how to handle NULL below.
Inserting with PreparedStatement
Never build SQL by concatenating or interpolating user input: "... WHERE name = '$name'" is an SQL injection hole. Use ? placeholders and bind values with the typed setXxx methods. Parameter indexes start at 1:
import java.math.BigDecimal
import java.sql.Statement
import java.sql.Types
import java.time.LocalDateTime
fun insertUser(conn: Connection, name: String, email: String, age: Int?, balance: BigDecimal): Long {
val sql = "INSERT INTO users (name, email, age, balance, created_at) VALUES (?, ?, ?, ?, ?)"
return conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS).use { ps ->
ps.setString(1, name)
ps.setString(2, email)
if (age != null) ps.setInt(3, age) else ps.setNull(3, Types.INTEGER)
ps.setBigDecimal(4, balance)
ps.setObject(5, LocalDateTime.of(2026, 10, 1, 9, 30))
ps.executeUpdate()
ps.generatedKeys.use { keys ->
check(keys.next()) { "no generated key" }
keys.getLong(1)
}
}
}
fun main() {
connect().use { conn ->
createSchema(conn)
println(insertUser(conn, "Ann", "ann@example.com", 34, BigDecimal("120.50")))
println(insertUser(conn, "Bob", "bob@example.com", null, BigDecimal("0.00")))
println(insertUser(conn, "Cid", "cid@example.com", 27, BigDecimal("75.25")))
}
}
1
2
3
RETURN_GENERATED_KEYS asks the driver to return the auto-generated id. Some drivers (PostgreSQL, Oracle) return all columns of the row unless you name the key columns: conn.prepareStatement(sql, arrayOf("id")). In PostgreSQL you can also write INSERT ... RETURNING id and call executeQuery().
setInt takes a non-null Int, so a nullable value needs an explicit setNull. setObject(index, value) accepts null with most drivers, which is convenient in helper functions.
Querying and mapping rows
executeQuery returns a ResultSet positioned before the first row. Call next() until it returns false, and read columns by name or by 1-based index:
import java.sql.ResultSet
data class User(
val id: Long,
val name: String,
val email: String,
val age: Int?,
val balance: BigDecimal,
val createdAt: LocalDateTime,
)
fun ResultSet.toUser() = User(
id = getLong("id"),
name = getString("name"),
email = getString("email"),
age = getObject("age", Int::class.javaObjectType),
balance = getBigDecimal("balance"),
createdAt = getObject("created_at", LocalDateTime::class.java),
)
fun findUsersOlderThan(conn: Connection, minAge: Int): List<User> =
conn.prepareStatement("SELECT * FROM users WHERE age > ? ORDER BY id").use { ps ->
ps.setInt(1, minAge)
ps.executeQuery().use { rs ->
buildList { while (rs.next()) add(rs.toUser()) }
}
}
fun main() {
connect().use { conn ->
findUsersOlderThan(conn, 30).forEach(::println)
}
}
User(id=1, name=Ann, email=ann@example.com, age=34, balance=120.50, createdAt=2026-10-01T09:30)
Bob's age is NULL, and NULL > 30 is not true in SQL, so he isn't returned.
NULL handling
The primitive getters can't return null: getInt, getLong, getDouble and getBoolean return 0 / false for SQL NULL. Reading Bob's age with getInt("age") silently gives 0. There are two correct ways to read a nullable number:
// 1. typed getObject (JDBC 4.1+), returns null for NULL
val age1: Int? = rs.getObject("age", Int::class.javaObjectType)
// 2. primitive getter followed by wasNull()
val raw = rs.getInt("age")
val age2: Int? = if (rs.wasNull()) null else raw
Reference-type getters (getString, getBigDecimal, getBytes, getTimestamp) return null directly. They are declared as platform types (String!), so Kotlin won't stop you from assigning them to a non-null String; if the column can be NULL, declare the property as String?, otherwise you get a NullPointerException at the assignment.
Int::class.javaObjectType is java.lang.Integer, the boxed type; Int::class.java would be the primitive int, which getObject can't return.
Single row and scalar queries
fun findUserByEmail(conn: Connection, email: String): User? =
conn.prepareStatement("SELECT * FROM users WHERE email = ?").use { ps ->
ps.setString(1, email)
ps.executeQuery().use { rs -> if (rs.next()) rs.toUser() else null }
}
fun countUsers(conn: Connection): Long =
conn.createStatement().use { st ->
st.executeQuery("SELECT COUNT(*) FROM users").use { rs ->
rs.next()
rs.getLong(1)
}
}
println(findUserByEmail(conn, "bob@example.com"))
println(findUserByEmail(conn, "nobody@example.com"))
println(countUsers(conn))
User(id=2, name=Bob, email=bob@example.com, age=null, balance=0.00, createdAt=2026-10-01T09:30)
null
3
Removing boilerplate with extension functions
The prepareStatement / bind / executeQuery / while (next()) / close pattern repeats in every query. A few extension functions on Connection cover most needs:
import java.sql.PreparedStatement
fun PreparedStatement.bind(params: Array<out Any?>): PreparedStatement {
params.forEachIndexed { i, p -> setObject(i + 1, p) }
return this
}
fun <T> Connection.query(sql: String, vararg params: Any?, mapper: (ResultSet) -> T): List<T> =
prepareStatement(sql).use { ps ->
ps.bind(params).executeQuery().use { rs ->
buildList { while (rs.next()) add(mapper(rs)) }
}
}
fun <T> Connection.queryOne(sql: String, vararg params: Any?, mapper: (ResultSet) -> T): T? =
query(sql, *params, mapper = mapper).firstOrNull()
fun Connection.update(sql: String, vararg params: Any?): Int =
prepareStatement(sql).use { it.bind(params).executeUpdate() }
Because the lambda comes after a vararg, it is passed outside the parentheses and the parameters stay positional:
fun main() {
connect().use { conn ->
val names = conn.query("SELECT name FROM users WHERE balance >= ? ORDER BY name", BigDecimal("50")) {
it.getString("name")
}
println(names)
val ann = conn.queryOne("SELECT * FROM users WHERE id = ?", 1L) { it.toUser() }
println(ann?.email)
val changed = conn.update("UPDATE users SET age = ? WHERE email = ?", 41, "bob@example.com")
println("updated $changed row(s)")
}
}
[Ann, Cid]
ann@example.com
updated 1 row(s)
queryOne above fetches every matching row; for large results add LIMIT 1 to the SQL or stop after the first next().
For huge result sets, return a lazy Sequence instead of a List, but make sure the caller consumes it before the ResultSet is closed, for example by taking a lambda that receives the sequence inside use. Some drivers buffer the whole result in memory unless you also call ps.fetchSize = 500 (PostgreSQL additionally requires auto-commit to be off for cursor-based fetching).
Transactions
To run several statements atomically, turn off auto-commit, then commit() on success or rollback() on failure. An inline helper makes it a one-liner at the call site:
inline fun <T> Connection.transaction(block: Connection.() -> T): T {
val previous = autoCommit
autoCommit = false
try {
val result = block()
commit()
return result
} catch (e: Throwable) {
rollback()
throw e
} finally {
autoCommit = previous
}
}
fun transfer(conn: Connection, fromId: Long, toId: Long, amount: BigDecimal) = conn.transaction {
update("UPDATE users SET balance = balance - ? WHERE id = ?", amount, fromId)
val balance = queryOne("SELECT balance FROM users WHERE id = ?", fromId) { it.getBigDecimal(1) }!!
require(balance.signum() >= 0) { "insufficient funds" }
update("UPDATE users SET balance = balance + ? WHERE id = ?", amount, toId)
}
fun main() {
connect().use { conn ->
transfer(conn, 1, 2, BigDecimal("20.00"))
try {
transfer(conn, 2, 3, BigDecimal("500.00"))
} catch (e: IllegalArgumentException) {
println("transfer failed: ${e.message}")
}
conn.query("SELECT name, balance FROM users ORDER BY id") {
"${it.getString(1)}: ${it.getBigDecimal(2)}"
}.forEach(::println)
}
}
transfer failed: insufficient funds
Ann: 100.50
Bob: 20.00
Cid: 75.25
The second transfer had already subtracted 500 from Bob when the check failed; rollback() undid it.
Other transaction controls:
conn.transactionIsolation = Connection.TRANSACTION_SERIALIZABLEchanges the isolation level (default is usuallyREAD_COMMITTED).val sp = conn.setSavepoint()andconn.rollback(sp)roll back part of a transaction.conn.isReadOnly = truehints that the transaction only reads, which some databases optimize.
Batch inserts
Sending rows one by one costs a network round trip per row. addBatch queues parameter sets and executeBatch sends them together. Combine it with a transaction for speed and atomicity:
fun insertMany(conn: Connection, users: List<Pair<String, String>>): Int = conn.transaction {
val sql = "INSERT INTO users (name, email, created_at) VALUES (?, ?, ?)"
prepareStatement(sql).use { ps ->
val now = LocalDateTime.of(2026, 10, 2, 12, 0)
for ((chunkIndex, chunk) in users.chunked(1000).withIndex()) {
for ((name, email) in chunk) {
ps.setString(1, name)
ps.setString(2, email)
ps.setObject(3, now)
ps.addBatch()
}
ps.executeBatch()
println("chunk $chunkIndex: ${chunk.size} rows")
}
}
users.size
}
fun main() {
connect().use { conn ->
val users = (1..2500).map { "user$it" to "user$it@example.com" }
println("inserted ${insertMany(conn, users)}")
println("total ${countUsers(conn)}")
}
}
chunk 0: 1000 rows
chunk 1: 1000 rows
chunk 2: 500 rows
inserted 2500
total 2503
Executing in chunks keeps memory bounded. The MySQL driver only rewrites batches into multi-row INSERTs with rewriteBatchedStatements=true in the URL; PostgreSQL has the similar reWriteBatchedInserts=true.
Type mappings
| SQL type | Setter / getter | Kotlin type |
|---|---|---|
INT, BIGINT |
setInt / getInt, setLong / getLong |
Int, Long |
DECIMAL, NUMERIC |
setBigDecimal / getBigDecimal |
BigDecimal |
DOUBLE, REAL |
setDouble / getDouble |
Double |
BOOLEAN |
setBoolean / getBoolean |
Boolean |
VARCHAR, TEXT |
setString / getString |
String |
VARBINARY, BLOB, bytea |
setBytes / getBytes |
ByteArray |
DATE |
setObject / getObject(i, LocalDate::class.java) |
LocalDate |
TIME |
setObject / getObject(i, LocalTime::class.java) |
LocalTime |
TIMESTAMP |
setObject / getObject(i, LocalDateTime::class.java) |
LocalDateTime |
TIMESTAMP WITH TIME ZONE |
setObject / getObject(i, OffsetDateTime::class.java) |
OffsetDateTime |
Use the java.time types through setObject / getObject(index, Class) instead of the legacy java.sql.Date, Time and Timestamp, which carry the JVM's default time zone around in confusing ways. To store an Instant, convert it with instant.atOffset(ZoneOffset.UTC) and use a TIMESTAMP WITH TIME ZONE column; Instant itself is not part of the JDBC spec, although some drivers accept it.
Use BigDecimal for money, never Double. See BigInteger and BigDecimal.
Handling errors
All failures are SQLExceptions. The message is driver-specific, but sqlState is a standardized five-character code whose first two characters give the class of error (23 = integrity constraint violation, 08 = connection problem, 40 = transaction rollback such as a deadlock):
import java.sql.SQLException
fun main() {
connect().use { conn ->
try {
insertUser(conn, "Ann again", "ann@example.com", 50, BigDecimal.ZERO)
} catch (e: SQLException) {
when (e.sqlState) {
"23505" -> println("email already registered")
else -> throw e
}
}
}
}
email already registered
23505 (unique violation) is used by PostgreSQL and H2. MySQL reports 23000 with vendor errorCode 1062, so check e.errorCode when you need to be precise across databases. Drivers may also chain several exceptions; iterate e.iterator() or follow e.nextException to see all of them.
Connection pooling with a DataSource
Opening a database connection takes milliseconds and server resources (a process per connection in PostgreSQL). In a server application, get connections from a pool instead of DriverManager. HikariCP is the standard choice:
import com.zaxxer.hikari.HikariConfig
import com.zaxxer.hikari.HikariDataSource
import javax.sql.DataSource
fun createDataSource(): HikariDataSource = HikariDataSource(
HikariConfig().apply {
jdbcUrl = URL
username = "sa"
password = ""
maximumPoolSize = 10
poolName = "app"
}
)
fun main() {
createDataSource().use { ds ->
// close() returns the connection to the pool instead of closing it
val n = ds.connection.use { conn -> countUsers(conn) }
println("users: $n")
}
}
All the code above takes a Connection, so it works unchanged with a pool. Code written against javax.sql.DataSource doesn't depend on Hikari and can be tested with any other implementation.
JDBC and coroutines
JDBC calls block the calling thread. In coroutine code (Ktor, Compose, any suspend function), run them on Dispatchers.IO so they don't block a thread meant for non-blocking work:
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
class UserRepository(private val ds: DataSource) {
suspend fun findById(id: Long): User? = withContext(Dispatchers.IO) {
ds.connection.use { conn ->
conn.queryOne("SELECT * FROM users WHERE id = ?", id) { it.toUser() }
}
}
}
Keep a whole transaction inside one withContext block; a Connection is not thread-safe and must not be shared by concurrent coroutines. Size the pool to match: if 64 coroutines wait for one of 10 connections, the rest block in getConnection() until the pool's timeout. For a fully non-blocking driver stack, look at R2DBC; see Coroutines for the basics.
When to use a library
Plain JDBC with a handful of helpers is fine for small services, scripts and tools. When the number of queries grows, consider:
- Exposed (JetBrains): Kotlin DSL and DAO layer over JDBC, shown in the PostgreSQL article.
- jOOQ: type-safe SQL generated from your schema.
- SQLDelight: write SQL files, get generated type-safe Kotlin APIs.
- Spring
JdbcClient: thin JDBC wrapper if you already use Spring.
All of them still use JDBC drivers and the same URLs, pools and transaction rules underneath.
Gotchas
- Close everything with
use. Closing aConnectioncloses its statements, but with a pool the connection is only returned, not closed, so close statements and result sets yourself. getIntreturns 0 for NULL. UsegetObject(col, Int::class.javaObjectType)orwasNull()for nullable columns.- Platform types.
getStringreturnsString!; assigning aNULLto a non-null property throwsNullPointerException. - Indexes start at 1 for both parameters and columns.
- Placeholders are for values only. You can't bind a table name, column name or
ORDER BYdirection with?; validate such identifiers against an allow-list before putting them in the SQL string. IN (?)takes one value. For a list, generateIN (?, ?, ?)withList(ids.size) { "?" }.joinToString(), or use= ANY(?)withconn.createArrayOf("bigint", ids.toTypedArray())in PostgreSQL.- Restore auto-commit after a manual transaction, especially with pooled connections, or the next borrower inherits an open transaction.
- Column labels are case-sensitive in some places.
getString("name")matches case-insensitively, butmetaData.getColumnLabel(i)returns the database's spelling (NAMEin H2 and Oracle,namein PostgreSQL).