Connect to PostgreSQL using pq
masterTo use pq with database/sql, import the driver with a blank identifier to register it. You can connect using a DSN string (key=value or postgresql:// URL) or by using the pq.Config struct.
Important: sql.Open() only creates a connection pool and does not establish a connection. Always call db.Ping() to verify the connection is actually working. It is also recommended to include connect_timeout in your DSN to prevent indefinite waits during asynchronous connection attempts.
package main
import (
"database/sql"
"log"
_ "github.com/lib/pq" // To register the driver.
)
func main() {
// Using DSN string
db, err := sql.Open("postgres", "host=localhost dbname=pqgo connect_timeout=5")
if err != nil {
log.Fatal(err)
}
defer db.Close()
// Verify connection
err = db.Ping()
if err != nil {
log.Fatal(err)
}
}