Skip to content

Instantly share code, notes, and snippets.

@ruseel
Last active May 4, 2016 02:36
Show Gist options
  • Save ruseel/c8b50fc4790360859d21 to your computer and use it in GitHub Desktop.
Save ruseel/c8b50fc4790360859d21 to your computer and use it in GitHub Desktop.
clojure에서 jdbc tutorial

WIP

embed H2를 사용해서 써보자.

Setup

lein new app clj-jdbc-tutorial

cd clj-jdbc-tutorial
vi project.clj

하고 project.clj에 dependancy 2개를 추가한다.

[org.clojure/java.jdbc "0.4.2"]
[com.h2database/h2 "1.4.190"]

REPL 실행

$ lein repl
nREPL server started on port 56736 on host 127.0.0.1 - nrepl://127.0.0.1:56736
REPL-y 0.3.7, nREPL 0.2.10
Clojure 1.7.0
Java HotSpot(TM) 64-Bit Server VM 1.8.0_60-b27
    Docs: (doc function-name-here)
          (find-doc "part-of-name-here")
  Source: (source function-name-here)
 Javadoc: (javadoc java-object-or-class-here)
    Exit: Control+D or (exit) or (quit)
 Results: Stored in vars *1, *2, *3, an exception in *e

clj-jdbc-tutorial.core=>

select

clj-jdbc-tutorial.core=> (require '[clojure.java.jdbc :as j])
nil
clj-jdbc-tutorial.core=> (j/query "jdbc:h2:./test" "select 1")
({:1 1})

create table

(j/execute! "jdbc:h2:./test" "create table a (id int primary key, field_a int)")

insert

;; sql을 그대로 쓰려면 이렇게 
(j/execute! "jdbc:h2:./test" "insert into a (field_a) values (1)")

;; prepared statement로 쓰려면 이렇게 
(j/execute! "jdbc:h2:./test" ["insert into a (field_a) values (?)" 2])

;; j/insert!로 쓰려면 이렇게 
(j/insert!  "jdbc:h2:./test" "a" { :field_a 3 })

Update

;; sql로 쓰려면 이렇게 
(j/execute! "jdbc:h2:./test" "update a set field_a = 3 where id = 1")

;; j/update!로 쓰려면 이렇게 
(j/update! "jdbc:h2:./test" "a" { :field_a 3 } ["ID = ?" 1])

PG로 접속하게 하려면

project.clj에 [postgresql/postgresql "9.1-901-1.jdbc4"] 를 추가하고

(def pg-db-uri "jdbc:postgres://user:password@host:port/dbname")
(def pg-db-spec 
  {:subprotocol "postgres"
   ...
   })
   
(j/query pg-db-uri "select 1")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment