英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论