Postgresql Database Interface on top of pgx
- You need an active running instance of Postgresql DB somewhere you can access
- (optional) Create
.env
file in your root directory and add below variables- PGUSER
- PGPASSWORD
- PGHOST
- PGDATABASE
- PGPORT
go get it (pun intended 😸)
go get github.com/junekimdev/dbi
package main
import (
"log"
"github.com/junekimdev/dbi"
"github.com/joho/godotenv"
)
func init(){
// Load environment variables
err := godotenv.Load(".env")
if err != nil {
log.Fatalf("Failed to load .env file: %v", err)
}
// Connect to DB with env
dbi.Connect(dbi.CreateURIFromEnv().String())
}
// User struct
type User struct {
id int
name string
gender string
}
func main() {
// Prep your sql
sql := "SELECT id, name, gender FROM test_user WHERE id=($1)"
// Query DB
result := Query(sql, 7)
// Destination of Scan
var user User
// Scan the result
// You Need to pass "scan function" that has "Scan" method of pgx.Rows
if err := Scan(result, func() { result.Scan(&user.id, &user.name, &user.gender) }); err != nil {
panic(err)
}
log.Printf("%#+v", user)
}