shad-go/lectures/07-sql/sqlx/structscan.go

33 lines
518 B
Go
Raw Normal View History

2020-04-09 11:15:34 +00:00
package sqlx
2020-04-08 19:20:23 +00:00
2020-04-09 11:15:34 +00:00
import (
"context"
"log"
2020-04-08 19:20:23 +00:00
2020-04-09 11:15:34 +00:00
"github.com/jmoiron/sqlx"
)
func Example(ctx context.Context, db *sqlx.DB) {
rows, err := db.QueryContext(ctx, "SELECT id, name FROM users WHERE id = $1", 1)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
var value struct {
ID int `db:"id"`
Name string `db:"name"`
}
if err := sqlx.StructScan(rows, &value); err != nil {
log.Fatal(err)
}
log.Println(value)
}
if err = rows.Err(); err != nil {
log.Fatal(err)
}
}