Reputation: 193
I followed a thread in here and came up with this
var b Button
queryErr := connection.QueryRow("SELECT id_printer, name, has_children FROM button WHERE id_parent IS NULL;").Scan(&b.ID, &b.Name, &b.Children)
if queryErr != nil {
response, err := json.MarshalIndent(b, "", " ")
fmt.Fprint(w, string(response))
if err != nil {
log.Println("Error on jsonmarshalindent Starter")
}
} else {
log.Println("Error on queryErr starter")
log.Println(queryErr)
fmt.Fprint(w, "Error getting starter button")
}
it has 2 problems:
the struct is
type Starter struct {
Buttons []Button `json:buttons`
}
type Button struct {
ID int `json:id`
Name string `json:name`
Children bool `json:children`
}
Can someone shed some light in this please?
Upvotes: 0
Views: 385
Reputation: 11626
For the bool, it depends on the type of the actual column. If it isn't boolean, it won't map directly.
You may need to store in a temporary variable first and then translate and assign to the field in Button to match.
As for reading all rows, here's an example adapted from the docs.
You use Query instead of QueryRow to get all rows.
rows, err := db.Query("SELECT id_printer, name, has_children FROM button WHERE id_parent IS NULL;")
if err != nil {
log.Fatal(err)
}
defer rows.Close()
var buttons []Button
for rows.Next() {
var b Button
if err := rows.Scan(&b.ID, &b.Name, &b.Children); err != nil {
log.Fatal(err)
}
buttons = append(buttons,b)
}
// At this point, you have all your rows in the "buttons" variable
Upvotes: 1