pgx for Go: Complete Guide with Examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction to pgx: A Powerful PostgreSQL Driver for Go

\n\n

The pgx library (PostgreSQL eXtended) is a modern, high-performance driver and toolkit for working with PostgreSQL from the Go programming language. Unlike the standard database/sql package, pgx provides direct access to the PostgreSQL protocol, offering significant performance gains and access to unique DBMS features such as LISTEN/NOTIFY, the COPY protocol, working with arrays and composite types, and much more.

\n\n

Why use pgx instead of the standard database/sql? First, pgx is 30-50% faster due to the absence of unnecessary abstractions. Second, it supports all modern features of PostgreSQL 12+ (and newer versions). Third, pgx provides a rich API for working with connections, connection pools, prepared queries, and transactions. Finally, pgx is fully compatible with database/sql through a special adapter, allowing its use in projects that already use the standard interface.

\n\n

Installing pgx

\n\n

Installing pgx into a Go project is done with the standard go get command. To work with PostgreSQL, you will need to install the main pgx package and possibly additional modules:

\n\n
# Install the main pgx v5 package (recommended version)\ngo get github.com/jackc/pgx/v5\n\n# Install the package for working with connection pools\ngo get github.com/jackc/pgx/v5/pgxpool\n\n# Install the adapter for compatibility with database/sql\ngo get github.com/jackc/pgx/v5/stdlib
\n\n

After running these commands, you will be able to import pgx into your Go files. Make sure you have Go version 1.18 or higher installed, as pgx v5 uses generics.

\n\n

Quick Start: First Connection to PostgreSQL

\n\n

Let's write a simple program that connects to a PostgreSQL database and executes a query. Assume you have PostgreSQL running on localhost:5432, the database is called testdb, the user is testuser with the password testpass.

\n\n
package main\n\nimport (\n    "context"\n    "fmt"\n    "log"\n    "os"\n\n    "github.com/jackc/pgx/v5"\n)\n\nfunc main() {\n    // Connection string\n    connStr := "postgres://testuser:testpass@localhost:5432/testdb"\n\n    // Establish connection\n    conn, err := pgx.Connect(context.Background(), connStr)\n    if err != nil {\n        log.Fatalf("Failed to connect to DB: %v", err)\n    }\n    defer conn.Close(context.Background())\n\n    // Execute a simple query\n    var greeting string\n    err = conn.QueryRow(context.Background(), "SELECT 'Hello, PostgreSQL!'").Scan(&greeting)\n    if err != nil {\n        log.Fatalf("Query execution error: %v", err)\n    }\n\n    fmt.Println(greeting)\n}
\n\n

This code establishes a connection, executes a query, and prints the result. Note the use of context.Background() — this is the standard way to pass context in Go, allowing you to control timeouts and cancel operations.

\n\n

Core Methods and Functions of pgx

\n\n

Let's look at the most important methods and functions of the pgx library. For each method, we provide a description, parameters, and a working code example.

\n\n

1. pgx.Connect — Establishing a Connection

\n

What it does: Creates a new connection to PostgreSQL. This is the primary way to start working with the database.

\n

Parameters:

\n
    \n
  • ctx context.Context — context for managing the connection's lifetime
  • \n
  • connString string — connection string in URI or DSN format
  • \n
\n

Returns: (*pgx.Conn, error)

\n

Example:

\n
conn, err := pgx.Connect(context.Background(), "postgres://user:pass@localhost:5432/mydb")\nif err != nil {\n    log.                    

Recommendations