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

25 lines
399 B
Go
Raw Normal View History

2020-04-09 11:15:34 +00:00
package prepare
import (
"context"
"database/sql"
"log"
)
2020-04-08 19:20:23 +00:00
2020-04-09 11:15:34 +00:00
func Prepare(ctx context.Context, db *sql.DB) {
stmt, err := db.PrepareContext(ctx, "SELECT name FROM users WHERE id = $1")
if err != nil {
log.Fatal(err)
}
defer stmt.Close()
2020-04-08 19:20:23 +00:00
2020-04-09 11:15:34 +00:00
for i := 1; ; i++ {
var name string
if err = stmt.QueryRowContext(ctx, i).Scan(&name); err != nil {
log.Fatal(err)
}
2020-04-08 19:20:23 +00:00
2020-04-09 11:15:34 +00:00
log.Println(name)
}
2020-04-08 19:20:23 +00:00
}