Use pgx.Connect with a connection string to establish a native PostgreSQL connection in Go. The native driver (pgx) is the default and recommended approach for v5.
package main
import (
"context"
"log"
"github.com/jackc/pgx/v5"
)
func main() {
conn, err := pgx.Connect(context.Background(), "host=localhost port=5432 user=postgres password=secret dbname=pgx_test")
if err != nil {
log.Fatalf("failed to connect: %v", err)
}
defer conn.Close(context.Background())
var result string
err = conn.QueryRow(context.Background(), "SELECT $1::text", "hello").Scan(&result)
if err != nil {
log.Fatalf("query failed: %v", err)
}
log.Println(result)
}
Install the driver first: go get github.com/jackc/pgx/v5.