Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "context"
- "database/sql"
- "fmt"
- "os"
- _ "github.com/lib/pq"
- )
- // User is a row from the `user` table.
- type User struct {
- userid int
- username string
- }
- /*
- This is the PostgreSQL table.
- lutz> select * from users limit 10;
- +----------+-------------+--------------+-------------+-------------+-----------+-----------------------------+--------------+-----------------+
- | userid | username | first_name | last_name | city | state | email | phone | is_like_sport |
- |----------+-------------+--------------+-------------+-------------+-----------+-----------------------------+--------------+-----------------|
- | 1 | cmelling0 | Caitrin | Melling | Cincinnati | Ohio | cmelling0@printfriendly.com | 513-466-6207 | True |
- | 2 | mbarkess1 | Margo | Barkess | Spring | Texas | mbarkess1@topsy.com | 409-737-5285 | True |
- | 3 | ssquibb2 | Sybille | Squibb | Tampa | Florida | ssquibb2@berkeley.edu | 813-195-3652 | False |
- | 4 | akirk3 | Atalanta | Kirk | Arlington | Virginia | akirk3@wikimedia.org | 571-945-2093 | True |
- | 5 | kelcomb4 | Krishna | Elcomb | Saint Paul | Minnesota | kelcomb4@example.com | 952-557-6819 | True |
- | 6 | lcoldbathe5 | Laure | Coldbathe | Cheyenne | Wyoming | lcoldbathe5@icq.com | 307-277-9971 | False |
- | 7 | ibutcher6 | Isa | Butcher | Punta Gorda | Florida | ibutcher6@mozilla.org | 941-900-2248 | False |
- | 8 | wdarnbrook7 | Whitman | Darnbrook | Miami | Florida | wdarnbrook7@csmonitor.com | 305-204-6425 | True |
- | 9 | bcoraini8 | Brenda | Coraini | Phoenix | Arizona | bcoraini8@wordpress.com | 602-642-5096 | True |
- | 10 | wplews9 | Ward | Plews | Nashville | Tennessee | wplews9@cafepress.com | 615-429-0570 | False |
- +----------+-------------+--------------+-------------+-------------+-----------+-----------------------------+--------------+-----------------+
- */
- func main() {
- db, err := sql.Open("postgres", "host=localhost")
- if err != nil {
- fmt.Printf("failed to open database connection: %s\n", err)
- os.Exit(1)
- }
- defer db.Close()
- ctx := context.Background()
- rows, err := db.QueryContext(ctx, "select userid, username from users limit 10")
- if err != nil {
- fmt.Printf("failed to get rows: %s\n", err)
- os.Exit(1)
- }
- defer rows.Close()
- for rows.NextResultSet() {
- if rows.Next() {
- var user User
- if err := rows.Scan(&user.userid, &user.username); err != nil {
- fmt.Printf("failed to scan user: %s\n", err)
- continue
- }
- fmt.Printf("%q\n", user)
- }
- }
- }
Add Comment
Please, Sign In to add comment