|
| 1 | +(ns pg2-core.main |
| 2 | + (:gen-class) |
| 3 | + (:require [pg.core :as pg] |
| 4 | + [pg.pool :as pool])) |
| 5 | + |
| 6 | +(def config |
| 7 | + {:host "localhost" |
| 8 | + :port 5432 |
| 9 | + :user "postgres" |
| 10 | + :password "password" |
| 11 | + :database "postgres-db"}) |
| 12 | + |
| 13 | +(defn create-connection [config] |
| 14 | + (pg/connect config)) |
| 15 | + |
| 16 | +(defn create-table! [conn] |
| 17 | + (pg/execute conn "DROP TABLE IF EXISTS students") |
| 18 | + (pg/execute conn "CREATE TABLE IF NOT EXISTS students (name VARCHAR(100) NOT NULL)")) |
| 19 | + |
| 20 | +(defn insert-student! [conn name] |
| 21 | + (pg/execute conn |
| 22 | + "INSERT INTO students (name) VALUES ($1) |
| 23 | + returning *" |
| 24 | + {:params [name]})) |
| 25 | + |
| 26 | +(defn lookup [conn name] |
| 27 | + (pg/execute conn |
| 28 | + "SELECT * FROM students WHERE name = $1" |
| 29 | + {:params [name]})) |
| 30 | + |
| 31 | +(defn using-conn [] |
| 32 | + (println "----Using Connection----") |
| 33 | + (println "PG2 Connection:" (create-connection config)) |
| 34 | + (let [conn (create-connection config)] |
| 35 | + (println "Table creation:" (create-table! conn)) |
| 36 | + (println "Student 'Manuel Gomes' inserted:" (insert-student! conn "Manuel Gomes")) |
| 37 | + (println "Query 'Manuel Gomes's Student entity:" (lookup conn "Manuel Gomes")) |
| 38 | + (println "Connection closed:" (nil? (pg/close conn))))) |
| 39 | + |
| 40 | +(defn using-conn-from-poll [] |
| 41 | + (println "----Using Connection Poll----") |
| 42 | + (pool/with-pool [pool config] |
| 43 | + (pool/with-connection [conn pool] |
| 44 | + (println "Table creation:" (create-table! conn)) |
| 45 | + (println "Student 'Manuel Gomes' inserted:" (insert-student! conn "Manuel Gomes")) |
| 46 | + (println "Query 'Manuel Gomes's Student entity:" (lookup conn "Manuel Gomes"))))) |
| 47 | + |
| 48 | +(defn -main [] |
| 49 | + (println "Hello GraalVM.") |
| 50 | + (using-conn) |
| 51 | + (using-conn-from-poll)) |
0 commit comments