shad-go/lectures/07-sql/query/query.go

30 lines
436 B
Go
Raw Normal View History

2020-04-09 11:15:34 +00:00
package query
2020-04-08 19:20:23 +00:00
2020-04-09 11:15:34 +00:00
import (
"context"
"database/sql"
"log"
)
2020-04-08 19:20:23 +00:00
2020-04-09 11:15:34 +00:00
func Query(ctx context.Context, db *sql.DB) {
2020-04-09 13:00:41 +00:00
rows, err := db.QueryContext(ctx, "SELECT id, name FROM users")
2020-04-09 11:15:34 +00:00
if err != nil {
log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
var id int
var name string
if err := rows.Scan(&id, &name); err != nil {
log.Fatal(err)
}
log.Println(id, name)
}
2020-04-08 19:20:23 +00:00
2020-04-09 11:15:34 +00:00
if err = rows.Err(); err != nil {
log.Fatal(err)
}
2020-04-08 19:20:23 +00:00
}