import ( "github.com/jmoiron/sqlx" _ "github.com/lib/pq" ) func main() { db, err := sqlx.Connect("postgres", "dbname=sample_db user=postgres password=secret host=localhost sslmode=disable") if err != nil { panic(err) } defer db.Close() }
type User struct { ID int `db:"id"` Name string `db:"name"` Email string `db:"email"` } func main() { db, _ := sqlx.Connect("postgres", "dbname=sample_db user=postgres password=secret host=localhost sslmode=disable") defer db.Close() var users []User err := db.Select(&users, "SELECT * FROM users") if err != nil { panic(err) } for _, user := range users { fmt.Printf("ID=%d, Name=%s, Email=%s\n", user.ID, user.Name, user.Email) } }In this example, we define a `User` struct that represents a database table with columns `id`, `name`, and `email`. We then use the `db.Select()` function to execute a SQL statement that retrieves all users from the database and maps them to the `users` slice of `User` structs. Finally, we loop through the `users` slice to print the values of each user. In summary, the go github.com.jmoiron.sqlx DB package provides a convenient interface for working with databases in Go, allowing developers to focus on business logic instead of dealing with low-level database operations.