// Start transaction tx, err := db.Beginx() if err != nil { log.Fatal(err) } // Define struct for query results type Person struct { Name string `db:"name"` Age int `db:"age"` } // Query database within transaction people := []Person{} err = tx.Select(&people, "SELECT name, age FROM people") if err != nil { tx.Rollback() log.Fatal(err) } // Commit transaction tx.Commit() // Print query results for _, p := range people { fmt.Printf("%s is %d years old\n", p.Name, p.Age) }
// Start transaction tx, err := db.Beginx() if err != nil { log.Fatal(err) } // Query database within transaction var count int err = tx.Get(&count, "SELECT COUNT(*) FROM people WHERE age >= ?", 18) if err != nil { tx.Rollback() log.Fatal(err) } // Commit transaction tx.Commit() // Print query results fmt.Printf("There are %d people over the age of 18\n", count)This code demonstrates how to query the "people" table within a SQL database using a transaction, and retrieve a single value (the count of people over the age of 18). The value is stored in a variable, and then printed.