简体   繁体   English

从PostGres DB获取结构

[英]Getting a struct from PostGres DB

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 b。儿童折断
  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. 例如,查询返回3行,但这取决于公司的客户,可以是3行或任意数字。

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? 有人可以对此有所启发吗?

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. 您可能需要先存储在一个临时变量中,然后再翻译并分配给Button中的字段以进行匹配。

As for reading all rows, here's an example adapted from the docs . 至于读取所有行,下面是从docs改编而成的示例。

You use Query instead of QueryRow to get all rows. 您使用Query而不是QueryRow来获取所有行。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM