Go - Postgresql connection
Go를 이용해서 Postgres DB 접속을 테스트 해 본다.
Go - Postgresql connection
go v1.20.2
Linux OS
개요
- Postgresql 연동을 위한 sample 코드로 진행
ref.
Connection to PostgreSQL
pq
library를 받아준다.
1
2
# Linux
root@ubuntu:~$ go get -u github.com/lib/pq
libarary import 후 진행
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// postgres_connection.go
// main
package main
// import library pacakge
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
)
// database/sql애서 사용되는 변수
const (
host = "postgresql-ha-pgpool.postgresql-ha.svc.cluster.local"
port = 5432
user = "postgres"
password = "wJ4P6g%uQm"
dbname = "postgres"
)
func main() {
// sslmode 기본 diable
psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
"password=%s dbname=%s sslmode=disable",
host, port, user, password, dbname)
db, err := sql.Open("postgres", psqlInfo)
if err != nil {
panic(err)
}
defer db.Close()
// error 처리
err = db.Ping()
if err != nil {
panic(err)
}
fmt.Println("Successfully connected!")
}
실행
1
2
root@ubuntu:~$ go run ./postgrtes_connection.go
Successfully connected!
This post is licensed under CC BY 4.0 by the author.