How to Use sqlx for Easier Database Access in Go

Use sqlx.Connect and sqlx.Select to map database rows directly to Go structs for cleaner code.

Use sqlx.Connect to open a connection and sqlx.Select to scan rows directly into Go structs.

import "github.com/jmoiron/sqlx"

type Person struct {
    FirstName string `db:"first_name"`
    LastName  string `db:"last_name"`
    Email     string
}

func main() {
    db, err := sqlx.Connect("postgres", "user=foo dbname=bar sslmode=disable")
    if err != nil { log.Fatal(err) }

    var people []Person
    err = db.Select(&people, "SELECT * FROM person ORDER BY first_name ASC")
    if err != nil { log.Fatal(err) }

    fmt.Printf("%#v\n", people[0])
}