dongzhun6952 2018-03-12 13:21
浏览 112
已采纳

在Golang中将结构与数据库创建绑定

How to bind data struct with database creation in Golang along with its tags/flags.

For example I have this code:

type User struct {
    ID      int     `sql:"primary_key;AUTO_INCREMENT"`
    Name    string  `sql:"type:varchar(100);unique"`
    Email   string  `sql:"type:varchar(100);unique"`
    Address string  `sql:"type:varchar(100)"`
}

When creating the database which should be based on this struct, I instead manually create it like this:

func (db *DB) CreateUserTable() (sql.Result, error) {

    statement := "CREATE TABLE IF NOT EXISTS %s (%s int, %s varchar, %s varchar, %s varchar)"
    return db.Exec(
        fmt.Sprintf(statement,
            "user",
            "id",
            "name",
            "email",
            "address",
        ),
    )
}

How to bind the struct and its tags(primary key, NULL, etc) in database creation?. Is there best practice for it without using ORM libraries(gorm,etc)?

  • 写回答

1条回答 默认 最新

  • duanchong3075 2018-03-16 08:28
    关注

    You can use reflect to examine the struct and use it to construct your database query.

    For example:

    If you want to read struct's name to use it as table name:

    tableName := reflect.TypeOf(your-struct).Name()
    

    If you want to read struct's properties, loop and read it by using:

    val := reflect.ValueOf(your-struct)
    for i:=0; i < val.NumField(); i++ {
        field := val.Type().Field(i)
        tag := field.Tag
    
        fieldType := field.Type // get struct's variable type
        fieldName := field.Name //get struct variable's name
        fieldByTag1 := tag.Get("your-tag") // get struct tag's name 
        fieldByTag2 := tag.Get("your-another-tag") // get another struct tag's name(if you have more)
    }
    

    Note that struct's tags are the one inside back tick -> `

    That's all you need to get from a struct. You should explore more in the documentation.

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

报告相同问题?

悬赏问题

  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题