Optimize database access in Go by using connection pooling, prepared statements, and batching to reduce latency and overhead. Configure the pool size and timeouts in your database/sql driver to match your workload.
import (
"database/sql"
_ "github.com/lib/pq"
)
func initDB() (*sql.DB, error) {
db, err := sql.Open("postgres", "user=postgres dbname=mydb sslmode=disable")
if err != nil {
return nil, err
}
db.SetMaxOpenConns(25)
db.SetMaxIdleConns(25)
db.SetConnMaxLifetime(5 * time.Minute)
return db, nil
}
- Use
db.SetMaxOpenConnsto limit concurrent connections and prevent resource exhaustion. - Use
db.SetMaxIdleConnsto keep a pool of ready connections for instant reuse. - Use
db.SetConnMaxLifetimeto close old connections and prevent stale network issues. - Use
db.Preparefor repeated queries to avoid parsing overhead on every execution. - Use
db.Execwith multiple placeholders to batch inserts instead of looping single inserts.