如何从Go结构体生成MySQL表

6
我正在使用Go创建一个CRUD程序,我有一个相当大的结构体,其中包含70多个字段,我想将其添加到MySQL数据库中。我想知道是否有一种自动映射结构体到数据库的方法,这样我就不必手动创建表格,而是直接复制我的结构体。
3个回答

4
我还没有找到完全自动化这个过程的方法,但是你可以使用标签和一点代码来创建它们。 解决方案示例: 有一些 GitHub 项目可以帮助你实现这一点。
例如:structable 你需要为结构体成员添加标签。
以下是 GitHub 上的示例:
type Stool struct {
  Id         int    `stbl:"id, PRIMARY_KEY, AUTO_INCREMENT"`
  Legs   int    `stbl:"number_of_legs"`
  Material string `stbl:"material"`
  Ignored  string // will not be stored. No tag.
}

当您拥有该部分时,您可以按照以下示例(也来自github页面)创建表格。
stool := new(Stool)
stool.Material = "Wood"
db := getDb() // Get a sql.Db. You're on  the hook to do this part.

// Create a new structable.Recorder and tell it to
// bind the given struct as a row in the given table.
r := structable.New(db, "mysql").Bind("test_table", stool)

// This will insert the stool into the test_table.
err := r.Insert()

2
尝试

gen-model

go get -u github.com/DaoYoung/gen-model
gen-model init # then set value in .gen-model.yaml
gen-model create

完成


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接