0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Exposedを使ってDBアクセス

Posted at

kotlinでのDBアクセスにExposedを使ったので忘備録。
動作確認にはDockerでテスト用のDBをたてて確認しました。

DOckerの環境構築は以下を参考にしました。
・WSL2とDockerの導入
https://qiita.com/KoKeCross/items/a6365af2594a102a817b

・WSL2のメモリ枯渇対策
https://qiita.com/yoichiwo7/items/e3e13b6fe2f32c4c6120

##Exposedとは
Kotlinで書かれたSQLライブラリです。
https://github.com/JetBrains/Exposed

##サンプルプログラム

まずはDockerでDBを作成するためのdocker-compose.yamlファイル。

version: '3'
services:
  db:
    image: postgres:12.3
    ports:
      - 5433:5432
    environment:
      POSTGRES_USER: admin
      POSTGRES_PASSWORD: admin
      POSTGRES_DB: test_db

次にテーブル定義。

object Member : Table("member") {
    val id = integer("member_id").autoIncrement().primaryKey()
    val name = varchar("name", 50)
    val age = integer("age")
}

最後にメイン関数。

import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.transactions.transaction
import org.jetbrains.exposed.sql.SchemUtils.create

fun main() {
    Database.connect("jdbc:postgresql://localhot:5433/test_db", "org.postgresql.Driver", "admin", "admin")

    transaction {
        addLogger(StdOutSqlLogger)

        create(Member)

        Member.insert {
            it[id] = 1
            it[name] = "abc"
            it[age] = 20
        }

        Member.insert {
            it[id] = 2
            it[name] = "efd"
            it[age] = 30
        }

        for(member in Member.selectAll()) {
            println("${member[Member.id]}: ${member[Member.name]}: ${member[Member.age]}")
        }

        Member.update({Member.name eq "abc"}) {
            it[name] = "あいうえお"
        }

        for(member in Member.selectAll()) {
            println("${member[Member.id]}: ${member[Member.name]}: ${member[Member.age]}")
        }

        Member.deleteAll()

        drop(Member)
    }
}

やっつけですが、とりあえず一通りCRUDができることを確認できました。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?