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)
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?