sql query

Fill in the blanks in line ABCD, to print out all the rows and potential errors.

  1. age := 27
  2. rows, err := db.Query("SELECT name FROM users WHERE age=?", age)
  3. if err != nil {
  4. log.Fatal(err)
  5. }
  6. defer ___ // A
  7. for ___ { //B
  8. var name string
  9. if err := ___; err != nil { //C
  10. log.Fatal(err)
  11. }
  12. fmt.Printf("%s is %d\n", name, age)
  13. }
  14. if err := ___; err != nil { //D
  15. log.Fatal(err)
  16. }

Answer

  1. age := 27
  2. rows, err := db.Query("SELECT name FROM users WHERE age=?", age)
  3. if err != nil {
  4. log.Fatal(err)
  5. }
  6. defer rows.Close()
  7. for rows.Next() {
  8. var name string
  9. if err := rows.Scan(&name); err != nil {
  10. log.Fatal(err)
  11. }
  12. fmt.Printf("%s is %d\n", name, age)
  13. }
  14. if err := rows.Err(); err != nil {
  15. log.Fatal(err)
  16. }