PostgreSQL Support in Go: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 3: Line 3:
* [[Database Support in Go]]
* [[Database Support in Go]]
* [[PostgreSQL]]
* [[PostgreSQL]]
=Open a Connection=
<syntaxhighlight lang='go'>
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 {
  // ...
}
</syntaxhighlight>
<code>sql.Open()</code> 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.

Revision as of 03:46, 14 October 2023

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.