Junior — Middle
What tool or package have you used to interact with the PostgreSQL database in your projects?
sobes.tech AI
Answer from AI
In Go projects, to interact with PostgreSQL, the database/sql package is often used together with the github.com/lib/pq driver. This driver implements the database/sql interface and allows executing SQL queries, managing transactions, and working with results.
Example of connecting and executing a simple query:
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()
var name string
err = db.QueryRow("SELECT name FROM users WHERE id = $1", 1).Scan(&name)
if err != nil {
log.Fatal(err)
}
log.Println("User name:", name)
}
Also popular are ORM libraries, such as GORM, which simplify working with the database, but for basic tasks, database/sql with the lib/pq driver is a standard and reliable choice.