Guest User

Untitled

a guest
Feb 1st, 2019
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.84 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "context"
  5. "database/sql"
  6. "fmt"
  7. "os"
  8.  
  9. _ "github.com/lib/pq"
  10. )
  11.  
  12. // User is a row from the `user` table.
  13. type User struct {
  14. userid int
  15. username string
  16. }
  17.  
  18. /*
  19. This is the PostgreSQL table.
  20.  
  21. lutz> select * from users limit 10;
  22. +----------+-------------+--------------+-------------+-------------+-----------+-----------------------------+--------------+-----------------+
  23. | userid | username | first_name | last_name | city | state | email | phone | is_like_sport |
  24. |----------+-------------+--------------+-------------+-------------+-----------+-----------------------------+--------------+-----------------|
  25. | 1 | cmelling0 | Caitrin | Melling | Cincinnati | Ohio | cmelling0@printfriendly.com | 513-466-6207 | True |
  26. | 2 | mbarkess1 | Margo | Barkess | Spring | Texas | mbarkess1@topsy.com | 409-737-5285 | True |
  27. | 3 | ssquibb2 | Sybille | Squibb | Tampa | Florida | ssquibb2@berkeley.edu | 813-195-3652 | False |
  28. | 4 | akirk3 | Atalanta | Kirk | Arlington | Virginia | akirk3@wikimedia.org | 571-945-2093 | True |
  29. | 5 | kelcomb4 | Krishna | Elcomb | Saint Paul | Minnesota | kelcomb4@example.com | 952-557-6819 | True |
  30. | 6 | lcoldbathe5 | Laure | Coldbathe | Cheyenne | Wyoming | lcoldbathe5@icq.com | 307-277-9971 | False |
  31. | 7 | ibutcher6 | Isa | Butcher | Punta Gorda | Florida | ibutcher6@mozilla.org | 941-900-2248 | False |
  32. | 8 | wdarnbrook7 | Whitman | Darnbrook | Miami | Florida | wdarnbrook7@csmonitor.com | 305-204-6425 | True |
  33. | 9 | bcoraini8 | Brenda | Coraini | Phoenix | Arizona | bcoraini8@wordpress.com | 602-642-5096 | True |
  34. | 10 | wplews9 | Ward | Plews | Nashville | Tennessee | wplews9@cafepress.com | 615-429-0570 | False |
  35. +----------+-------------+--------------+-------------+-------------+-----------+-----------------------------+--------------+-----------------+
  36. */
  37.  
  38. func main() {
  39. db, err := sql.Open("postgres", "host=localhost")
  40. if err != nil {
  41. fmt.Printf("failed to open database connection: %s\n", err)
  42. os.Exit(1)
  43. }
  44. defer db.Close()
  45.  
  46. ctx := context.Background()
  47. rows, err := db.QueryContext(ctx, "select userid, username from users limit 10")
  48. if err != nil {
  49. fmt.Printf("failed to get rows: %s\n", err)
  50. os.Exit(1)
  51. }
  52. defer rows.Close()
  53.  
  54. for rows.NextResultSet() {
  55. if rows.Next() {
  56. var user User
  57. if err := rows.Scan(&user.userid, &user.username); err != nil {
  58. fmt.Printf("failed to scan user: %s\n", err)
  59. continue
  60. }
  61. fmt.Printf("%q\n", user)
  62. }
  63. }
  64.  
  65. }
Add Comment
Please, Sign In to add comment