Skip to content

Instantly share code, notes, and snippets.

@ngsw-taro
Last active December 20, 2015 14:48
Show Gist options
  • Save ngsw-taro/6149089 to your computer and use it in GitHub Desktop.
Save ngsw-taro/6149089 to your computer and use it in GitHub Desktop.
KotlinでDBアクセス
// 原始的でシンプルな方法
package com.taroid.sample
import java.sql.DriverManager
import java.sql.ResultSet
import java.sql.Statement
import java.sql.Connection
fun main(args: Array<String>) {
val articles = findAllArticles()
println(articles)
}
fun findAllArticles(): List<Article> {
var conn: Connection? = null
var statement: Statement? = null
var resultSet: ResultSet? = null
val articleListBuilder = ImmutableArrayListBuilder<Article>()
try {
conn = DriverManager.getConnection("jdbc:postgresql://localhost/sample")
statement = conn?.createStatement()
resultSet = statement?.executeQuery("select * from articles")
while(resultSet?.next() ?: false) {
articleListBuilder.add(Article(
resultSet!!.getLong(1),
resultSet!!.getString(2)!!,
resultSet!!.getString(3) ?: "",
resultSet!!.getString(4)!!
))
}
} finally {
resultSet?.close()
statement?.close()
conn?.close()
}
return articleListBuilder.build()
}
data class Article(
val id: Long,
val title: String,
val author: String,
val content: String
)
// kotlin.jdbcライブラリを使った方法
package com.taroid.sample
import kotlin.jdbc.getConnection
import kotlin.jdbc.use
import kotlin.jdbc.useSql
import kotlin.jdbc.iterator
fun main(args: Array<String>) {
val articles = findAllArticles()
println(articles)
}
fun findAllArticles(): List<Article> {
val articleListBuilder = ImmutableArrayListBuilder<Article>()
getConnection("jdbc:postgresql://localhost/sample").use {
// useSql -> use にリネーム予定
it.createStatement()?.useSql {
it.executeQuery("select * from articles").use {
it.iterator().forEach {
articleListBuilder.add(Article(
it.getLong(1),
it.getString(2)!!,
it.getString(3) ?: "",
it.getString(4)!!
))
}
}
}
}
return articleListBuilder.build()
}
data class Article(
val id: Long,
val title: String,
val author: String,
val content: String
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment