How do I open and pool connections using pgx?

Learn how to open and pool connections using the pgx library in Go. This guide will help you understand the basics of database connectivity in Go applications and demonstrate efficient connection management.

pgx, Golang, database connection, connection pooling, Go database, PostgreSQL, Go pgx example

          package main

          import (
              "context"
              "log"
              "github.com/jackc/pgx/v4/pgxpool"
          )

          func main() {
              // Set up a connection pool
              config, err := pgxpool.ParseConfig("postgres://user:password@localhost:5432/database_name")
              if err != nil {
                  log.Fatalf("Unable to parse config: %v\n", err)
              }

              pool, err := pgxpool.ConnectConfig(context.Background(), config)
              if err != nil {
                  log.Fatalf("Unable to connect to database: %v\n", err)
              }
              defer pool.Close()

              // Use the pool to execute a query
              var greeting string
              err = pool.QueryRow(context.Background(), "SELECT 'Hello, World!'").Scan(&greeting)
              if err != nil {
                  log.Fatalf("QueryRow failed: %v\n", err)
              }
              log.Println(greeting)
          }
        

pgx Golang database connection connection pooling Go database PostgreSQL Go pgx example