PostgreSQL Support in Go

From NovaOrdis Knowledge Base
Revision as of 03:46, 14 October 2023 by Ovidiu (talk | contribs) (→‎Internal)
Jump to navigation Jump to search

Internal


Open a Connection

import (
  "database/sql"
  _ "github.com/lib/pq"
)

...

role := "ovidiu"
password := "something"
databaseHost := "localhost"
databaseName := "testdb"
url := fmt.Sprintf("postgres://%s:%s@%s/%s?sslmode=disable", role, password, databaseHost, databaseName)
db, err := sql.Open("postgres", url)
if err != nil {
  // ...
}
defer func() {
  if err := db.Close(); err != nil {
    // ...
  }
}()

err = db.Ping()
if err != nil {
  // ...
}

sql.Open() returns a database handle. The implementation maintains a pool of zero or more underlying connections, and it is safe for concurrent use by multiple goroutines.