Skip to content

Instantly share code, notes, and snippets.

@KenjiOhtsuka
Created October 30, 2018 18:40
Show Gist options
  • Save KenjiOhtsuka/16e28d58882ef6bd49bd512e14cecd2e to your computer and use it in GitHub Desktop.
Save KenjiOhtsuka/16e28d58882ef6bd49bd512e14cecd2e to your computer and use it in GitHub Desktop.
Kotlin prepared statement (SQL)
package com.improve_future.sample
import java.io.Closeable
import java.sql.DriverManager
import java.sql.Statement
import java.text.SimpleDateFormat
class Connection(private val coreConnection: java.sql.Connection) :
java.sql.Connection by coreConnection, Closeable {
override fun close() {
coreConnection.close()
}
override fun createStatement(): Statement {
return coreConnection.createStatement()
}
}
fun connect(): Connection {
val url = "jdbc:postgresql://HOST:5432/DB_NAME"
val user = "USER_NAME"
val password = "PASSWORD"
val c = DriverManager.getConnection(url, user, password)
c.autoCommit = false
return Connection(c)
}
fun main(args: Array<String>) {
example()
}
fun example() {
connect().use {
val st1 = it.createStatement()
val resultSet1 = st1.executeQuery(
"""
SELECT a, b
FROM table_name
WHERE value = 5
ORDER BY id
""".trimIndent()
}
while (resultSet1.next()) {
val a = resultSet1.getLong("a") // same as resultSet1.getLong(1)
val b = resultSet1.getString("b") // same as resultSet1.getString(2)
// process
}
resultSet1.close()
st1.close()
val st2 = it.prepareStatement(
"""
SELECT a, b
FROM table_name
WHERE value = 5
AND filter_1 = ?
AND filter_2 = ?
ORDER BY id
""".trimIndent()
)
st2.setLong(1, 1L)
st2.setString(2, "text")
resultSet2 = st2.executeQuery()
while (resultSet2.next()) {
val a = resultSet1.getLong("a") // same as resultSet1.getLong(1)
val b = resultSet1.getString("b") // same as resultSet1.getString(2)
// process
}
resultSet2.close()
st2.close()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment