pgx¶
About
pgx is a pure Go driver and toolkit for PostgreSQL.
Features
Support for approximately 70 different PostgreSQL types
Connection pool with after-connect hook for arbitrary connection setup
Adapter for Go’s standard
database/sqlinterfaceAutomatic statement preparation and caching
Single-round trip query mode
Full TLS connection control
Tracing and logging support
Batch queries
… and many more.
Synopsis
example.go
package main
import (
"context"
"fmt"
"github.com/jackc/pgx/v5"
)
func main() {
ctx := context.Background()
// Connect to database.
conn, _ := pgx.Connect(ctx, "postgresql://crate:crate@localhost:5432/?sslmode=disable")
defer conn.Close(ctx)
// Invoke basic query.
rows, _ := conn.Query(ctx, "SELECT mountain, height FROM sys.summits ORDER BY height DESC LIMIT 3")
defer rows.Close(ctx)
// Display results.
for rows.Next() {
var mountain string
var height int
rows.Scan(&mountain, &height)
fmt.Println(mountain, height)
}
}
SSL connection
Use the sslmode=require parameter, and replace username, password,
and hostname with values matching your environment.
Also use this variant to connect to CrateDB Cloud.
conn, _ := pgx.Connect(ctx, "postgresql://admin:password@testcluster.cratedb.net:5432/?sslmode=require")
Quickstart example
Create the file example.go including the synopsis code shared above.
Start CrateDB using Docker or Podman, then invoke the example program.
docker run --rm --publish=5432:5432 docker.io/crate '-Cdiscovery.type=single-node'
go mod init github.com/cratedb-guide/connect/go/pgx
go mod tidy
go run example.go
Full example
Connect to CrateDB and CrateDB Cloud using Go.