dongmi6102 2017-09-16 16:46
浏览 89
已采纳

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

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条回答 默认 最新

  • dongzao4503 2017-09-16 20:50
    关注

    generate struct fields dynamically

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

    But please: Don't do it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题