github.com/rakyll/go@v0.0.0-20170216000551-64c02460d703/src/database/sql/example_test.go (about)

     1  // Copyright 2013 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package sql_test
     6  
     7  import (
     8  	"database/sql"
     9  	"fmt"
    10  	"log"
    11  )
    12  
    13  var db *sql.DB
    14  
    15  func ExampleDB_Query() {
    16  	age := 27
    17  	rows, err := db.Query("SELECT name FROM users WHERE age=?", age)
    18  	if err != nil {
    19  		log.Fatal(err)
    20  	}
    21  	defer rows.Close()
    22  	for rows.Next() {
    23  		var name string
    24  		if err := rows.Scan(&name); err != nil {
    25  			log.Fatal(err)
    26  		}
    27  		fmt.Printf("%s is %d\n", name, age)
    28  	}
    29  	if err := rows.Err(); err != nil {
    30  		log.Fatal(err)
    31  	}
    32  }
    33  
    34  func ExampleDB_QueryRow() {
    35  	id := 123
    36  	var username string
    37  	err := db.QueryRow("SELECT username FROM users WHERE id=?", id).Scan(&username)
    38  	switch {
    39  	case err == sql.ErrNoRows:
    40  		log.Printf("No user with that ID.")
    41  	case err != nil:
    42  		log.Fatal(err)
    43  	default:
    44  		fmt.Printf("Username is %s\n", username)
    45  	}
    46  }
    47  
    48  func ExampleDB_Query_multipleResultSets() {
    49  	age := 27
    50  	q := `
    51  create temp table uid (id bigint); -- Create temp table for queries.
    52  insert into uid
    53  select id from users where age < ?; -- Populate temp table.
    54  
    55  -- First result set.
    56  select
    57  	users.id, name
    58  from
    59  	users
    60  	join uid on users.id = uid.id
    61  ;
    62  
    63  -- Second result set.
    64  select 
    65  	ur.user, ur.role
    66  from
    67  	user_roles as ur
    68  	join uid on uid.id = ur.user
    69  ;
    70  	`
    71  	rows, err := db.Query(q, age)
    72  	if err != nil {
    73  		log.Fatal(err)
    74  	}
    75  	defer rows.Close()
    76  
    77  	for rows.Next() {
    78  		var (
    79  			id   int64
    80  			name string
    81  		)
    82  		if err := rows.Scan(&id, &name); err != nil {
    83  			log.Fatal(err)
    84  		}
    85  		fmt.Printf("id %d name is %s\n", id, name)
    86  	}
    87  	if !rows.NextResultSet() {
    88  		log.Fatal("expected more result sets", rows.Err())
    89  	}
    90  	var roleMap = map[int64]string{
    91  		1: "user",
    92  		2: "admin",
    93  		3: "gopher",
    94  	}
    95  	for rows.Next() {
    96  		var (
    97  			id   int64
    98  			role int64
    99  		)
   100  		if err := rows.Scan(&id, &role); err != nil {
   101  			log.Fatal(err)
   102  		}
   103  		fmt.Printf("id %d has role %s\n", id, roleMap[role])
   104  	}
   105  	if err := rows.Err(); err != nil {
   106  		log.Fatal(err)
   107  	}
   108  }