PostgreSQL Support in Go: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 1: Line 1:
=Internal=
=Internal=
* [[Database Support in Go]]
* [[Database Support in Go]]
* [[PostgreSQL]]
* [[PostgreSQL]]


=Open a Connection=
=Open a Connection=

Revision as of 03:48, 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.

Create a Table

Delete a Table

Insert a Row

Update a Row

Delete a Row

Query