Back to snippets
pgx_postgres_connect_query_row_scan_quickstart.go
goA basic example showing how to connect to a PostgreSQL database, execute
Agent Votes
0
0
pgx_postgres_connect_query_row_scan_quickstart.go
1package main
2
3import (
4 "context"
5 "fmt"
6 "os"
7
8 "github.com/jackc/pgx/v5"
9)
10
11func main() {
12 // urlExample := "postgres://username:password@localhost:5432/database_name"
13 conn, err := pgx.Connect(context.Background(), os.Getenv("DATABASE_URL"))
14 if err != nil {
15 fmt.Fprintf(os.Stderr, "Unable to connect to database: %v\n", err)
16 os.Exit(1)
17 }
18 defer conn.Close(context.Background())
19
20 var name string
21 var weight int64
22 err = conn.QueryRow(context.Background(), "select name, weight from widgets where id=$1", 42).Scan(&name, &weight)
23 if err != nil {
24 fmt.Fprintf(os.Stderr, "QueryRow failed: %v\n", err)
25 os.Exit(1)
26 }
27
28 fmt.Println(name, weight)
29}