Junior — Middle
Can you name popular libraries used for interacting with PostgreSQL database?
sobes.tech AI
Answer from AI
To work with PostgreSQL in Go, the following libraries are often used:
database/sqltogether with thelib/pqdriver — a standard approach for interacting with the database via the SQL interface.pgx— a more modern and performant driver and client for PostgreSQL, which can be used both withdatabase/sqland independently.- ORM libraries, such as
GORMorEnt, which simplify database operations by providing an object-oriented interface.
Example of connecting using pgx:
import (
"context"
"github.com/jackc/pgx/v4"
"log"
)
func main() {
conn, err := pgx.Connect(context.Background(), "postgres://user:password@localhost:5432/dbname")
if err != nil {
log.Fatal(err)
}
defer conn.Close(context.Background())
var greeting string
err = conn.QueryRow(context.Background(), "select 'Hello, PostgreSQL!' ").Scan(&greeting)
if err != nil {
log.Fatal(err)
}
log.Println(greeting)
}