Sobes.tech
Junior — Middle

How are requests sent to the PostgreSQL database?

sobes.tech AI

Answer from AI

In Go, to send requests to a PostgreSQL database, the database/sql package is usually used along with a driver, for example, github.com/lib/pq.

Main steps:

  1. Import the driver and database/sql.
  2. Open a connection using sql.Open.
  3. Execute queries using methods like Query, Exec, or QueryRow.
  4. Process the results.

Example:

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

func main() {
    connStr := "user=username dbname=mydb sslmode=disable"
    db, err := sql.Open("postgres", connStr)
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()

    rows, err := db.Query("SELECT id, name FROM users WHERE active = $1", true)
    if err != nil {
        log.Fatal(err)
    }
    defer rows.Close()

    for rows.Next() {
        var id int
        var name string
        if err := rows.Scan(&id, &name); err != nil {
            log.Fatal(err)
        }
        log.Println(id, name)
    }
}

Thus, interaction with PostgreSQL in Go boils down to using the standard database/sql interface and the appropriate driver.

How are requests sent to the PostgreSQL database… - sobes.tech