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:
- Import the driver and
database/sql. - Open a connection using
sql.Open. - Execute queries using methods like
Query,Exec, orQueryRow. - 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.