0

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:

  1. It breaks on b.Children
  2. I don't know how to make it dynamically. for instance, the query returns 3 rows, but it depends on the company's client, it can be 3 or any number.

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?

4
  • i ment, build or convert a struct from a postgres db Commented Dec 8, 2015 at 0:28
  • 1
    Your conditional is incorrect. You've got if queryErr != nil ... but the block beneath that is for when the error is actually nil. Perhaps fixing that will print the underlying error for you to diagnose. We will need to know what "it breaks" means. Surely theres a panic or something that is being hidden by that incorrect conditional. Commented Dec 8, 2015 at 0:33
  • I also strongly recommend using sqlx (github.com/jmoiron/sqlx) - which can help turn query-results-into-structs. Commented Dec 8, 2015 at 1:11
  • @SimonWhitehead thanks! that solved the error, now i just need to make it handle more than 1 row Commented Dec 8, 2015 at 10:53

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

this along with @SimonWhitehead solved the issue, thanks!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.