MySQL
suggest changeMySQL is one of the most widely deployed relational databases. Kotlin on the JVM talks to it through JDBC with the official driver, MySQL Connector/J. The same driver works with MariaDB for everything shown here; MariaDB also ships its own org.mariadb.jdbc:mariadb-java-client.
This article covers what is specific to MySQL:
- connection URLs and the driver properties that matter
AUTO_INCREMENTkeys (MySQL has noRETURNING)- upserts with
INSERT ... ON DUPLICATE KEY UPDATE - fast batch inserts with
rewriteBatchedStatements - transactions, row locks and retrying deadlocks
- MySQL error codes
DATETIMEvsTIMESTAMPand time zonesJSONcolumns- streaming large results
- HikariCP and JetBrains Exposed with MySQL
The general JDBC API (use, ResultSet mapping, extension helpers) is covered in JDBC from Kotlin. For other databases see PostgreSQL and SQLite.
All examples below were run against MySQL 9.7 with Connector/J 26.7.
Dependencies
// build.gradle.kts
dependencies {
implementation("com.mysql:mysql-connector-j:26.7.0")
// connection pool
implementation("com.zaxxer:HikariCP:7.1.0")
// optional: type-safe SQL DSL from JetBrains
val exposedVersion = "1.6.0"
implementation("org.jetbrains.exposed:exposed-core:$exposedVersion")
implementation("org.jetbrains.exposed:exposed-jdbc:$exposedVersion")
implementation("org.jetbrains.exposed:exposed-java-time:$exposedVersion")
}
The driver artifact used to be mysql:mysql-connector-java. That coordinate is no longer updated, so use com.mysql:mysql-connector-j. Connector/J now uses year-based version numbers (8.x, then 9.x, then 26.x).
To follow along, create a database and a user (as the MySQL root user):
CREATE DATABASE shop;
CREATE USER 'app'@'%' IDENTIFIED BY 'secret';
GRANT ALL ON shop.* TO 'app'@'%';
Connecting
A MySQL JDBC URL looks like jdbc:mysql://host:port/database?prop1=value&prop2=value. The default port is 3306. The driver registers itself, so no Class.forName call is needed:
import java.sql.DriverManager
const val URL = "jdbc:mysql://localhost:3306/shop"
fun main() {
DriverManager.getConnection(URL, "app", "secret").use { conn ->
val meta = conn.metaData
println("server: ${meta.databaseProductName} ${meta.databaseProductVersion}")
println("driver: ${meta.driverName} ${meta.driverVersion}")
println("catalog: ${conn.catalog}")
conn.createStatement().use { st ->
st.executeQuery("SELECT @@character_set_server, @@transaction_isolation, @@sql_mode").use { rs ->
rs.next()
println("charset: ${rs.getString(1)}")
println("isolation: ${rs.getString(2)}")
println("sql_mode: ${rs.getString(3)}")
}
}
}
}
Output:
server: MySQL 9.7.2
driver: MySQL Connector/J mysql-connector-j-26.7.0 (Revision: 559f62df01d4f618440da174ff45ba87f7b3b2a8)
catalog: shop
charset: utf8mb4
isolation: REPEATABLE-READ
sql_mode: ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION
Things worth knowing from that output:
utf8mb4is the default character set since MySQL 8.0. It is real UTF-8 (including emoji). The oldutf8is an alias forutf8mb3, which only stores up to 3 bytes per character. Don't use it.- The default isolation level is
REPEATABLE READ, notREAD COMMITTEDas in PostgreSQL. STRICT_TRANS_TABLESmakes MySQL reject bad data (too-long strings, invalid dates) instead of silently truncating it. Keep it on.
Useful connection properties:
| Property | Purpose |
|---|---|
sslMode=REQUIRED / VERIFY_IDENTITY |
require TLS / also verify the server certificate and host name |
connectionTimeZone=UTC |
time zone the driver uses to convert TIMESTAMP values (see below) |
forceConnectionTimeZoneToSession=true |
also set the session time_zone to match |
rewriteBatchedStatements=true |
turn JDBC batches into multi-row INSERTs (much faster) |
useCursorFetch=true |
let fetchSize stream results with a server-side cursor |
allowPublicKeyRetrieval=true |
needed for caching_sha2_password users over non-TLS connections. Only use it on trusted networks |
connectTimeout=5000, socketTimeout=30000 |
timeouts in milliseconds |
Creating tables and getting generated keys
MySQL has no RETURNING clause. To get an AUTO_INCREMENT id, pass Statement.RETURN_GENERATED_KEYS and read generatedKeys:
import java.math.BigDecimal
import java.sql.Connection
import java.sql.DriverManager
import java.sql.Statement
const val URL = "jdbc:mysql://localhost:3306/shop"
fun createSchema(conn: Connection) {
conn.createStatement().use { st ->
st.execute("DROP TABLE IF EXISTS order_items, orders, products")
st.execute(
"""
CREATE TABLE products (
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
sku VARCHAR(32) NOT NULL UNIQUE,
name VARCHAR(200) NOT NULL,
notes TEXT NULL,
price DECIMAL(10,2) NOT NULL,
stock INT NOT NULL DEFAULT 0,
created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
"""
)
}
}
fun insertProduct(conn: Connection, sku: String, name: String, price: BigDecimal, stock: Int): Long {
val sql = "INSERT INTO products (sku, name, price, stock) VALUES (?, ?, ?, ?)"
conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS).use { ps ->
ps.setString(1, sku)
ps.setString(2, name)
ps.setBigDecimal(3, price)
ps.setInt(4, stock)
ps.executeUpdate()
ps.generatedKeys.use { keys ->
keys.next()
return keys.getLong(1)
}
}
}
fun main() {
DriverManager.getConnection(URL, "app", "secret").use { conn ->
createSchema(conn)
val a = insertProduct(conn, "KB-01", "Mechanical keyboard", BigDecimal("89.90"), 12)
val b = insertProduct(conn, "MS-02", "Wireless mouse", BigDecimal("24.50"), 40)
val c = insertProduct(conn, "MN-03", "27\" monitor", BigDecimal("279.00"), 3)
println("inserted ids: $a, $b, $c")
}
}
Output:
inserted ids: 1, 2, 3
Notes on the DDL:
ENGINE=InnoDBis the default. It is the only engine with transactions and foreign keys, so state it explicitly for clarity.DECIMAL(10,2)maps toBigDecimal. Never store money inFLOAT/DOUBLE.DATETIME(3)keeps milliseconds. Without a precision, MySQL truncates to whole seconds.BIGINT UNSIGNEDis fine for ids:getLongworks as long as the values stay belowLong.MAX_VALUE.
The rest of the examples use this products table.
Querying and mapping rows
Map rows with a small ResultSet extension. getObject(column, LocalDateTime::class.java) returns java.time types directly:
import java.math.BigDecimal
import java.sql.DriverManager
import java.sql.ResultSet
import java.time.LocalDateTime
const val URL = "jdbc:mysql://localhost:3306/shop"
data class Product(
val id: Long,
val sku: String,
val name: String,
val notes: String?,
val price: BigDecimal,
val stock: Int,
val createdAt: LocalDateTime,
)
fun ResultSet.toProduct() = Product(
id = getLong("id"),
sku = getString("sku"),
name = getString("name"),
notes = getString("notes"), // null for SQL NULL
price = getBigDecimal("price"),
stock = getInt("stock"),
createdAt = getObject("created_at", LocalDateTime::class.java),
)
fun main() {
DriverManager.getConnection(URL, "app", "secret").use { conn ->
conn.prepareStatement("UPDATE products SET notes = ? WHERE sku = ?").use { ps ->
ps.setString(1, "RGB backlight")
ps.setString(2, "KB-01")
ps.executeUpdate()
}
val sql = "SELECT * FROM products WHERE price < ? ORDER BY price"
val cheap = conn.prepareStatement(sql).use { ps ->
ps.setBigDecimal(1, BigDecimal("100"))
ps.executeQuery().use { rs ->
buildList { while (rs.next()) add(rs.toProduct()) }
}
}
for (p in cheap) {
println("${p.sku} ${p.name} ${p.price} stock=${p.stock} notes=${p.notes}")
}
println("createdAt type: ${cheap.first().createdAt::class.simpleName}")
}
}
Output:
MS-02 Wireless mouse 24.50 stock=40 notes=null
KB-01 Mechanical keyboard 89.90 stock=12 notes=RGB backlight
createdAt type: LocalDateTime
getString returns null for SQL NULL. Primitive getters like getInt return 0, so call rs.wasNull() or use getObject(col, Integer::class.java) when the column is nullable.
Upserts: INSERT ... ON DUPLICATE KEY UPDATE
MySQL's upsert fires when an insert would violate a PRIMARY KEY or UNIQUE index. Since MySQL 8.0.19 you refer to the new row with an alias (AS new). The older VALUES(col) function is deprecated:
import java.sql.DriverManager
const val URL = "jdbc:mysql://localhost:3306/shop"
fun main() {
DriverManager.getConnection(URL, "app", "secret").use { conn ->
val upsert = """
INSERT INTO products (sku, name, price, stock) VALUES (?, ?, ?, ?) AS new
ON DUPLICATE KEY UPDATE
price = new.price,
stock = products.stock + new.stock
"""
fun restock(sku: String, name: String, price: String, qty: Int) =
conn.prepareStatement(upsert).use { ps ->
ps.setString(1, sku)
ps.setString(2, name)
ps.setBigDecimal(3, price.toBigDecimal())
ps.setInt(4, qty)
ps.executeUpdate()
}
println("new row: " + restock("HD-04", "Headphones", "59.00", 10))
println("updated: " + restock("HD-04", "Headphones", "54.00", 5))
println("no change: " + restock("HD-04", "Headphones", "54.00", 0))
val ignored = conn.prepareStatement("INSERT IGNORE INTO products (sku, name, price) VALUES (?, ?, ?)").use { ps ->
ps.setString(1, "HD-04")
ps.setString(2, "Duplicate")
ps.setBigDecimal(3, "1.00".toBigDecimal())
ps.executeUpdate()
}
println("ignored: $ignored")
conn.createStatement().use { st ->
st.executeQuery("SELECT name, price, stock FROM products WHERE sku = 'HD-04'").use { rs ->
rs.next()
println("${rs.getString(1)} ${rs.getBigDecimal(2)} stock=${rs.getInt(3)}")
}
}
}
}
Output:
new row: 1
updated: 2
no change: 1
ignored: 0
Headphones 54.00 stock=15
What the update counts mean:
1means a new row was inserted.2means an existing row was updated.- Unchanged rows: the MySQL docs say
0, but Connector/J reports1. It connects with the "found rows" flag by default, soexecuteUpdatecounts matched rows, not changed ones. AdduseAffectedRows=trueto the URL to get the server's real affected-row count. INSERT IGNOREskipped the duplicate and returned0. Be careful: it also turns other errors (like too-long values) into warnings. PreferON DUPLICATE KEY UPDATE id = idwhen you just want to skip duplicates.
ON DUPLICATE KEY UPDATE and INSERT IGNORE use up an AUTO_INCREMENT value even when no row is inserted, so ids will have gaps. That is normal: never rely on ids being consecutive.
Fast batch inserts
By default Connector/J sends each statement in a JDBC batch separately. With rewriteBatchedStatements=true it rewrites the batch into multi-row INSERT ... VALUES (...), (...), ... statements:
import java.sql.DriverManager
import java.sql.Statement
import kotlin.time.measureTime
const val URL = "jdbc:mysql://localhost:3306/shop"
fun insertBatch(url: String, prefix: String, count: Int): List<Long> =
DriverManager.getConnection(url, "app", "secret").use { conn ->
conn.autoCommit = false
val sql = "INSERT INTO products (sku, name, price, stock) VALUES (?, ?, ?, ?)"
val ids = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS).use { ps ->
for (i in 1..count) {
ps.setString(1, "$prefix-$i")
ps.setString(2, "Item $i")
ps.setBigDecimal(3, (i % 50 + 0.99).toBigDecimal())
ps.setInt(4, i % 7)
ps.addBatch()
}
ps.executeBatch()
ps.generatedKeys.use { rs -> buildList { while (rs.next()) add(rs.getLong(1)) } }
}
conn.commit()
ids
}
fun main() {
lateinit var ids: List<Long>
val plain = measureTime { ids = insertBatch(URL, "P", 5000) }
println("plain batch: $plain, ${ids.size} keys, first=${ids.first()}")
val rewritten = measureTime {
ids = insertBatch("$URL?rewriteBatchedStatements=true", "R", 5000)
}
println("rewritten batch: $rewritten, ${ids.size} keys, first=${ids.first()}")
}
Output (timings vary):
plain batch: 1.760763900s, 5000 keys, first=8
rewritten batch: 142.417600ms, 5000 keys, first=5008
That is more than 10x faster for the same code. Generated keys still work with rewritten batches. The ids start at 8 because the upserts above used up a few values. Run batches inside a transaction (autoCommit = false) so that InnoDB doesn't flush to disk after every row.
Transactions and row locks
SELECT ... FOR UPDATE locks the selected rows until the transaction ends. This prevents two concurrent orders from both seeing "1 in stock". Here is a small inTransaction helper and an order placement:
import java.sql.Connection
import java.sql.DriverManager
import java.sql.Statement
const val URL = "jdbc:mysql://localhost:3306/shop"
class OutOfStock(sku: String) : Exception("not enough stock for $sku")
inline fun <T> Connection.inTransaction(block: Connection.() -> T): T {
val oldAutoCommit = autoCommit
autoCommit = false
try {
return block().also { commit() }
} catch (e: Throwable) {
rollback()
throw e
} finally {
autoCommit = oldAutoCommit
}
}
fun placeOrder(conn: Connection, customer: String, sku: String, qty: Int): Long = conn.inTransaction {
// lock the product row until commit/rollback
val (productId, stock) = prepareStatement(
"SELECT id, stock FROM products WHERE sku = ? FOR UPDATE"
).use { ps ->
ps.setString(1, sku)
ps.executeQuery().use { rs ->
require(rs.next()) { "unknown sku $sku" }
rs.getLong(1) to rs.getInt(2)
}
}
if (stock < qty) throw OutOfStock(sku)
prepareStatement("UPDATE products SET stock = stock - ? WHERE id = ?").use { ps ->
ps.setInt(1, qty)
ps.setLong(2, productId)
ps.executeUpdate()
}
val orderId = prepareStatement(
"INSERT INTO orders (customer) VALUES (?)", Statement.RETURN_GENERATED_KEYS
).use { ps ->
ps.setString(1, customer)
ps.executeUpdate()
ps.generatedKeys.use { it.next(); it.getLong(1) }
}
prepareStatement("INSERT INTO order_items (order_id, product_id, qty) VALUES (?, ?, ?)").use { ps ->
ps.setLong(1, orderId)
ps.setLong(2, productId)
ps.setInt(3, qty)
ps.executeUpdate()
}
orderId
}
fun stockOf(conn: Connection, sku: String): Int =
conn.prepareStatement("SELECT stock FROM products WHERE sku = ?").use { ps ->
ps.setString(1, sku)
ps.executeQuery().use { it.next(); it.getInt(1) }
}
fun main() {
DriverManager.getConnection(URL, "app", "secret").use { conn ->
conn.createStatement().use { st ->
st.execute("DROP TABLE IF EXISTS order_items, orders")
st.execute("""
CREATE TABLE orders (
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
customer VARCHAR(100) NOT NULL
)""")
st.execute("""
CREATE TABLE order_items (
order_id BIGINT UNSIGNED NOT NULL,
product_id BIGINT UNSIGNED NOT NULL,
qty INT NOT NULL,
PRIMARY KEY (order_id, product_id),
FOREIGN KEY (order_id) REFERENCES orders(id) ON DELETE CASCADE,
FOREIGN KEY (product_id) REFERENCES products(id)
)""")
}
println("order ${placeOrder(conn, "alice", "MN-03", 2)} placed")
println("stock left: ${stockOf(conn, "MN-03")}")
try {
placeOrder(conn, "bob", "MN-03", 2)
} catch (e: OutOfStock) {
println("failed: ${e.message}")
}
println("stock left: ${stockOf(conn, "MN-03")}")
conn.createStatement().use { st ->
st.executeQuery("SELECT COUNT(*) FROM orders").use { it.next(); println("orders: ${it.getInt(1)}") }
}
}
}
Output:
order 1 placed
stock left: 1
failed: not enough stock for MN-03
stock left: 1
orders: 1
The failed order threw before anything was written, and the rollback undid any partial work. Other useful locking reads are FOR SHARE (others can read but not modify), and FOR UPDATE SKIP LOCKED / NOWAIT for job queues.
DDL statements (CREATE, ALTER, DROP) cause an implicit commit in MySQL. They cannot be rolled back as part of a transaction.
Handling MySQL errors
Every error is a SQLException. errorCode holds the MySQL-specific number and sqlState the standard 5-character code. Connector/J also throws more specific subclasses:
import java.sql.Connection
import java.sql.DriverManager
import java.sql.SQLException
const val URL = "jdbc:mysql://localhost:3306/shop"
fun tryExec(conn: Connection, sql: String) {
try {
conn.createStatement().use { it.executeUpdate(sql) }
println("ok")
} catch (e: SQLException) {
val kind = when (e.errorCode) {
1062 -> "duplicate key"
1406 -> "value too long"
1452 -> "missing parent row"
1451 -> "row is still referenced"
1213 -> "deadlock, retry"
1205 -> "lock wait timeout"
else -> "other"
}
println("${e.javaClass.simpleName} code=${e.errorCode} state=${e.sqlState} ($kind)")
println(" ${e.message}")
}
}
fun main() {
DriverManager.getConnection(URL, "app", "secret").use { conn ->
tryExec(conn, "INSERT INTO products (sku, name, price) VALUES ('KB-01', 'Dup', 1)")
tryExec(conn, "INSERT INTO products (sku, name, price) VALUES ('${"X".repeat(40)}', 'Long', 1)")
tryExec(conn, "INSERT INTO order_items (order_id, product_id, qty) VALUES (999, 1, 1)")
tryExec(conn, "DELETE FROM products WHERE sku = 'MN-03'")
}
}
Output:
SQLIntegrityConstraintViolationException code=1062 state=23000 (duplicate key)
Duplicate entry 'KB-01' for key 'products.sku'
MysqlDataTruncation code=1406 state=22001 (value too long)
Data truncation: Data too long for column 'sku' at row 1
SQLIntegrityConstraintViolationException code=1452 state=23000 (missing parent row)
Cannot add or update a child row: a foreign key constraint fails (`shop`.`order_items`, CONSTRAINT `order_items_ibfk_1` FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`) ON DELETE CASCADE)
SQLIntegrityConstraintViolationException code=1451 state=23000 (row is still referenced)
Cannot delete or update a parent row: a foreign key constraint fails (`shop`.`order_items`, CONSTRAINT `order_items_ibfk_2` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`))
The codes you will see most often:
| Code | Meaning |
|---|---|
| 1062 | duplicate entry for a UNIQUE/PRIMARY KEY |
| 1406 | data too long for column (strict mode) |
| 1451 / 1452 | foreign key violation (parent referenced / parent missing) |
| 1213 | deadlock detected, the transaction was rolled back |
| 1205 | lock wait timeout exceeded |
| 1045 | access denied (bad user or password) |
| 1049 | unknown database |
Catching SQLIntegrityConstraintViolationException is the clean way to turn "username already taken" into a user-facing error. Don't run a SELECT first: that check has a race.
Retrying deadlocks
InnoDB detects deadlocks immediately and rolls back one of the transactions with error 1213. The right response is to retry the whole transaction. This example forces a deadlock with two threads that lock the same two rows in opposite order:
import java.sql.Connection
import java.sql.DriverManager
import java.sql.SQLException
import java.util.concurrent.CyclicBarrier
import kotlin.concurrent.thread
const val URL = "jdbc:mysql://localhost:3306/shop"
fun <T> withRetry(name: String, attempts: Int = 3, block: () -> T): T {
repeat(attempts - 1) { attempt ->
try {
return block()
} catch (e: SQLException) {
if (e.errorCode != 1213 && e.errorCode != 1205) throw e
println("$name: ${e.javaClass.simpleName} (${e.errorCode}), retry ${attempt + 1}")
Thread.sleep(50L * (attempt + 1))
}
}
return block()
}
fun transfer(conn: Connection, from: String, to: String, qty: Int, barrier: CyclicBarrier?) {
conn.autoCommit = false
try {
conn.prepareStatement("UPDATE products SET stock = stock - ? WHERE sku = ?").use { ps ->
ps.setInt(1, qty); ps.setString(2, from); ps.executeUpdate()
}
barrier?.await() // make both threads hold their first lock
conn.prepareStatement("UPDATE products SET stock = stock + ? WHERE sku = ?").use { ps ->
ps.setInt(1, qty); ps.setString(2, to); ps.executeUpdate()
}
conn.commit()
} catch (e: Exception) {
conn.rollback()
throw e
} finally {
conn.autoCommit = true
}
}
fun main() {
val barrier = CyclicBarrier(2)
val workers = listOf("KB-01" to "MS-02", "MS-02" to "KB-01").mapIndexed { i, (from, to) ->
thread(name = "t$i") {
DriverManager.getConnection(URL, "app", "secret").use { conn ->
var first = true
withRetry("t$i") {
val b = if (first) barrier else null
first = false
transfer(conn, from, to, 1, b)
}
println("t$i: committed")
}
}
}
workers.forEach { it.join() }
}
Output (which thread loses varies):
t1: committed
t0: MySQLTransactionRollbackException (1213), retry 1
t0: committed
Retry the whole transaction, not just the failed statement, because InnoDB has already rolled back everything. Locking rows in a consistent order (for example, by id) makes deadlocks rarer, but you still need the retry.
Dates, times and time zones
MySQL has two date-time types that behave differently:
DATETIMEstores a wall-clock value with no time zone. Map it toLocalDateTime.TIMESTAMPstores a point in time. It is converted from the session time zone to UTC on write and back on read. Map it toInstant/OffsetDateTime. Its range ends in 2038, so many schemas useDATETIMEand always store UTC.
Connector/J converts TIMESTAMP values using connectionTimeZone, which defaults to the JVM's time zone. Pin both the driver and the session to UTC so that results don't depend on where the app runs:
import java.sql.DriverManager
import java.time.Instant
import java.time.LocalDateTime
import java.time.OffsetDateTime
import java.util.TimeZone
const val URL = "jdbc:mysql://localhost:3306/shop"
fun main() {
TimeZone.setDefault(TimeZone.getTimeZone("America/New_York")) // pretend the app runs in New York
val url = "$URL?connectionTimeZone=UTC&forceConnectionTimeZoneToSession=true"
DriverManager.getConnection(url, "app", "secret").use { conn ->
conn.createStatement().use { st ->
st.execute("DROP TABLE IF EXISTS events")
st.execute("CREATE TABLE events (id INT PRIMARY KEY, local_dt DATETIME, ts TIMESTAMP(3))")
}
val instant = Instant.parse("2026-10-17T12:30:00Z")
conn.prepareStatement("INSERT INTO events VALUES (1, ?, ?)").use { ps ->
ps.setObject(1, LocalDateTime.of(2026, 10, 17, 9, 0)) // wall-clock time, no zone
ps.setObject(2, instant) // a point in time
ps.executeUpdate()
}
conn.createStatement().use { st ->
st.executeQuery("SELECT @@session.time_zone, local_dt, ts, CAST(ts AS CHAR) FROM events").use { rs ->
rs.next()
println("session tz: ${rs.getString(1)}")
println("local_dt: ${rs.getObject(2, LocalDateTime::class.java)}")
val odt = rs.getObject(3, OffsetDateTime::class.java) // getObject(Instant) is not supported
println("ts offset: $odt")
println("ts instant: ${odt.toInstant()}")
println("ts as text: ${rs.getString(4)}")
}
}
}
}
Output:
session tz: +00:00
local_dt: 2026-10-17T09:00
ts offset: 2026-10-17T12:30Z
ts instant: 2026-10-17T12:30:00Z
ts as text: 2026-10-17 12:30:00.000
Even though the JVM runs in New York, the instant round-trips exactly. setObject(Instant) works for writing. For reading, ask for OffsetDateTime and call toInstant(), because getObject(col, Instant::class.java) throws "Conversion not supported". For more on java.time see Dates and time.
Connection pool and JSON columns
In a server application use a connection pool. These Connector/J properties are the ones HikariCP recommends for MySQL. The example also shows the native JSON type:
import com.zaxxer.hikari.HikariConfig
import com.zaxxer.hikari.HikariDataSource
fun main() {
val config = HikariConfig().apply {
jdbcUrl = "jdbc:mysql://localhost:3306/shop"
username = "app"
password = "secret"
maximumPoolSize = 10
poolName = "shop-pool"
// Connector/J tuning recommended by HikariCP
addDataSourceProperty("cachePrepStmts", "true")
addDataSourceProperty("prepStmtCacheSize", "250")
addDataSourceProperty("prepStmtCacheSqlLimit", "2048")
addDataSourceProperty("useServerPrepStmts", "true")
addDataSourceProperty("rewriteBatchedStatements", "true")
addDataSourceProperty("connectionTimeZone", "UTC")
addDataSourceProperty("forceConnectionTimeZoneToSession", "true")
}
HikariDataSource(config).use { ds ->
ds.connection.use { conn ->
conn.createStatement().use { st ->
st.execute("DROP TABLE IF EXISTS settings")
st.execute("CREATE TABLE settings (user_id INT PRIMARY KEY, prefs JSON NOT NULL)")
}
conn.prepareStatement("INSERT INTO settings VALUES (?, ?)").use { ps ->
val rows = mapOf(
1 to """{"theme": "dark", "langs": ["en", "pl"], "beta": true}""",
2 to """{"theme": "light", "langs": ["de"], "beta": false}""",
3 to """{"theme": "dark", "langs": [], "beta": false}""",
)
for ((id, json) in rows) {
ps.setInt(1, id)
ps.setString(2, json)
ps.addBatch()
}
ps.executeBatch()
}
}
// borrow another connection from the pool
ds.connection.use { conn ->
val sql = """
SELECT user_id, prefs->>'$.theme', JSON_LENGTH(prefs->'$.langs'), prefs
FROM settings
WHERE prefs->>'$.theme' = ?
ORDER BY user_id
"""
conn.prepareStatement(sql).use { ps ->
ps.setString(1, "dark")
ps.executeQuery().use { rs ->
while (rs.next()) {
println("user ${rs.getInt(1)}: theme=${rs.getString(2)} langs=${rs.getInt(3)} raw=${rs.getString(4)}")
}
}
}
}
}
}
Output:
user 1: theme=dark langs=2 raw={"beta": true, "langs": ["en", "pl"], "theme": "dark"}
user 3: theme=dark langs=0 raw={"beta": false, "langs": [], "theme": "dark"}
About the JSON type:
- Send and receive JSON as a
String(use a library such as kotlinx.serialization to convert it, see JSON). MySQL validates it on insert. col->'$.path'extracts a JSON value.col->>'$.path'extracts and unquotes it to plain text.- MySQL stores JSON in a binary format and normalizes it: keys come back sorted and duplicates are removed. Don't expect your original formatting back.
- To index a JSON field, add a generated column (
theme VARCHAR(20) AS (prefs->>'$.theme') STORED) and index that.
HikariDataSource is AutoCloseable, so use shuts the pool down. Size the pool well below the server's max_connections (151 by default), keeping in mind every app instance has its own pool.
Streaming large results
Connector/J reads the entire result set into memory by default, and fetchSize is ignored. For big queries, either add useCursorFetch=true to the URL and set a positive fetchSize, or set fetchSize = Int.MIN_VALUE to stream row by row:
import java.sql.DriverManager
const val URL = "jdbc:mysql://localhost:3306/shop"
fun main() {
// useCursorFetch=true makes setFetchSize() use a server-side cursor
DriverManager.getConnection("$URL?useCursorFetch=true", "app", "secret").use { conn ->
conn.prepareStatement("SELECT id, sku, stock FROM products ORDER BY id").use { ps ->
ps.fetchSize = 500 // rows per round trip
ps.executeQuery().use { rs ->
var rows = 0
var totalStock = 0L
while (rs.next()) {
rows++
totalStock += rs.getInt("stock")
}
println("streamed $rows rows, total stock $totalStock")
}
}
}
}
Output:
streamed 10004 rows, total stock 30062
With Int.MIN_VALUE streaming, the connection can't run any other statement until you have read or closed the result set. Cursor fetch doesn't have that limit, but it uses a temporary table on the server.
JetBrains Exposed with MySQL
Exposed detects the MySQL dialect from the connection and generates MySQL SQL: backtick quoting, AUTO_INCREMENT, and ON DUPLICATE KEY UPDATE for upsert:
import com.zaxxer.hikari.HikariConfig
import com.zaxxer.hikari.HikariDataSource
import org.jetbrains.exposed.v1.core.*
import org.jetbrains.exposed.v1.javatime.CurrentDateTime
import org.jetbrains.exposed.v1.javatime.datetime
import org.jetbrains.exposed.v1.jdbc.*
import org.jetbrains.exposed.v1.jdbc.transactions.transaction
object Authors : Table("authors") {
val id = integer("id").autoIncrement()
val name = varchar("name", 100).uniqueIndex()
override val primaryKey = PrimaryKey(id)
}
object Books : Table("books") {
val id = integer("id").autoIncrement()
val authorId = integer("author_id").references(Authors.id)
val title = varchar("title", 200)
val price = decimal("price", 8, 2)
val addedAt = datetime("added_at").defaultExpression(CurrentDateTime)
override val primaryKey = PrimaryKey(id)
}
fun main() {
val ds = HikariDataSource(HikariConfig().apply {
jdbcUrl = "jdbc:mysql://localhost:3306/shop"
username = "app"
password = "secret"
maximumPoolSize = 5
})
val db = Database.connect(ds)
println("dialect: ${db.dialect.name}")
transaction(db) {
SchemaUtils.drop(Books, Authors)
SchemaUtils.create(Authors, Books)
val orwell = Authors.insert { it[name] = "George Orwell" } get Authors.id
val huxley = Authors.insert { it[name] = "Aldous Huxley" } get Authors.id
Books.batchInsert(
listOf(
Triple(orwell, "1984", "9.99"),
Triple(orwell, "Animal Farm", "7.50"),
Triple(huxley, "Brave New World", "8.25"),
)
) { (author, title, price) ->
this[Books.authorId] = author
this[Books.title] = title
this[Books.price] = price.toBigDecimal()
}
addLogger(StdOutSqlLogger) // print the SQL Exposed generates from here on
// INSERT ... ON DUPLICATE KEY UPDATE on MySQL
Authors.upsert { it[name] = "George Orwell" }
val bookCount = Books.id.count()
val rows = (Authors innerJoin Books)
.select(Authors.name, bookCount)
.groupBy(Authors.name)
.orderBy(Authors.name)
for (row in rows) println("${row[Authors.name]}: ${row[bookCount]} books")
Books.update({ Books.price less "9.00".toBigDecimal() }) {
it[price] = price * "1.10".toBigDecimal()
}
Books.selectAll().orderBy(Books.title).forEach {
println("${it[Books.title]} ${it[Books.price]}")
}
}
ds.close()
}
Output:
dialect: MySQL
SQL: INSERT INTO authors (`name`) VALUES ('George Orwell') AS NEW ON DUPLICATE KEY UPDATE `name`=NEW.`name`
SQL: SELECT authors.`name`, COUNT(books.id) FROM authors INNER JOIN books ON authors.id = books.author_id GROUP BY authors.`name` ORDER BY authors.`name` ASC
Aldous Huxley: 1 books
George Orwell: 2 books
SQL: UPDATE books SET price=(books.price * 1.10) WHERE books.price < 9.00
SQL: SELECT books.id, books.author_id, books.title, books.price, books.added_at FROM books ORDER BY books.title ASC
1984 9.99
Animal Farm 8.25
Brave New World 9.08
Exposed's transaction { } is blocking. In coroutine code, run JDBC work on Dispatchers.IO (see JDBC from Kotlin) or use Exposed's suspendTransaction.
Gotchas
- Use
utf8mb4, notutf8, for databases, tables and connections.utf8(utf8mb3) can't store emoji and many CJK characters. - Collation affects comparisons. The default
utf8mb4_0900_ai_ciis case- and accent-insensitive, so'abc' = 'ABC'is true and aUNIQUEindex treats them as duplicates. Useutf8mb4_binorutf8mb4_0900_as_csfor columns where case matters. - Unchanged rows count as updated.
executeUpdatereturns matched rows unless you adduseAffectedRows=true. - Batches are slow without
rewriteBatchedStatements=true. - Large
SELECTs load into memory unless you use cursor fetch or streaming. TIMESTAMPdepends on time zones and ends in 2038. SetconnectionTimeZone=UTC&forceConnectionTimeZoneToSession=true, or useDATETIMEand store UTC.- DDL commits implicitly. A failed migration halfway through can't be rolled back, so keep migration steps small (Flyway and Liquibase both support MySQL).
- Retry on 1213 and 1205. Deadlocks are a normal event under concurrency in InnoDB, not a bug.
allowPublicKeyRetrieval=trueerrors ("Public Key Retrieval is not allowed") come fromcaching_sha2_passwordover non-TLS connections. The proper fix issslMode=REQUIRED.- Never build SQL with string templates from user input. Always use
PreparedStatementparameters or Exposed.