动态生成结构字段从SQL QueryRow结果

huangapple go评论77阅读模式
英文:

Dynamically generate struct fields from SQL QueryRow result

问题

我想检索行的所有字段,然后将它们呈现为HTML。我知道如何做,以下是一个具有3个字段的行的代码示例:

type View struct {
    Id                  int
    Name_and_requisits  string
    Reg_Date            string
}

func getViewById(id int) (*View, error) {
    var vie View
    row := db.QueryRow("select id, name_and_requisits, reg_date from book where id = ?;", id)
    err := row.Scan(&vie.Id, &vie.Name_and_requisites, &vie.Reg_Date)
    if err != nil {
        return nil, err
    }

    return &vie, nil
}

但是在我的表中,一行包含大约20个列,我需要它们以及它们的名称,但我不想创建一个嵌套的硬编码结构。我有一个想法,可以根据列名动态生成结构字段,然后在其上使用row.Scan。有什么想法吗?也许对于这种情况来说,使用映射(map)更好?

谢谢!

英文:

I want to retrieve all fields of the row and than render them to html. I know how to do it and here is a code for a row with 3 fields:

type View struct {
	Id         int
	Name_and_requisits string
	Reg_Date  string
}
func getViewById(id int) (*View, error){
	var vie View
	row := db.QueryRow("select id, name_and_requisits, reg_date from book where id = ?;", id)
	err := row.Scan(&vie.Id, &vie.Name_and_requisites, &vie.Reg_Date)
	if err != nil {
		return nil, err
	}

	return &vie, nil
}

But in my table one row includes about 20 columns and i need all of them with their names but i dont want to create a nasted hardcoded struct. I have an idea like to generate struct fields dynamically, from names of columns, and than use row.Scan on it. Any ideas? Maybe map is better for this situation?

Thanks!

答案1

得分: 3

生成动态结构字段

https://golang.org/pkg/reflect/#StructOf

但请注意:不要这样做。

英文:

> generate struct fields dynamically

https://golang.org/pkg/reflect/#StructOf

But please: Don't do it.

huangapple
  • 本文由 发表于 2017年9月17日 00:46:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/46256197.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定