rows, err := db.Query("SELECT id, name FROM users") if err != nil { log.Fatal(err) } defer rows.Close() for rows.Next() { var id int var name string err := rows.Scan(&id, &name) if err != nil { log.Fatal(err) } fmt.Println(id, name) } if err := rows.Err(); err != nil { log.Fatal(err) }
row := db.QueryRow("SELECT COUNT(*) FROM users") var count int err := row.Scan(&count) if err != nil { log.Fatal(err) } fmt.Println(count)
rows, err := db.Queryx("SELECT id, name FROM users") if err != nil { log.Fatal(err) } defer rows.Close() for rows.Next() { var user User err := rows.StructScan(&user) if err != nil { log.Fatal(err) } fmt.Println(user.ID, user.Name) } if err := rows.Err(); err != nil { log.Fatal(err) }
rows, err := db.NamedQuery(`SELECT * FROM users WHERE name=:name AND age>=:age`, map[string]interface{}{ "name": "John", "age": 25, }) if err != nil { log.Fatal(err) } defer rows.Close() for rows.Next() { var user map[string]interface{} err := rows.MapScan(user) if err != nil { log.Fatal(err) } fmt.Println(user["id"], user["name"], user["age"]) } if err := rows.Err(); err != nil { log.Fatal(err) }In this example, the Rows.Next method of the sqlx package is used to loop through the result set returned by a named SQL query with parameters. For each row in the result set, the values of all columns are extracted using the rows.MapScan method, which automatically maps them into a map[string]interface{} object. Finally, the values of the "id", "name", and "age" columns are printed to the console.