package main import ( "database/sql" "fmt" _ "github.com/lib/pq" "github.com/jmoiron/sqlx" ) func main() { db, err := sqlx.Open("postgres", "host=localhost port=5432 user=postgres password=postgres dbname=mydb sslmode=disable") if err != nil { fmt.Println("Failed to connect to database:", err) return } defer db.Close() // Use the db object as needed }
package main import ( "database/sql" "fmt" _ "github.com/lib/pq" "github.com/jmoiron/sqlx" ) type User struct { ID int `db:"id"` Name string `db:"name"` Email string `db:"email"` } func main() { db, err := sqlx.Open("postgres", "host=localhost port=5432 user=postgres password=postgres dbname=mydb sslmode=disable") if err != nil { fmt.Println("Failed to connect to database:", err) return } defer db.Close() // SELECT * FROM users var users []User err = db.Select(&users, "SELECT * FROM users") if err != nil { fmt.Println("Failed to get users:", err) return } for _, user := range users { fmt.Println(user) } }In the above examples, the package used is `github.com.jmoiron.sqlx`. These examples show how to connect to a PostgreSQL database and query data using the `sqlx.DB` object. The package provides a cleaner API for running queries and returning results in a format suitable for use in Go code.