如何从Go结构生成MySQL表

时间:2019-03-02 12:08:03

标签: mysql go

我正在使用Go创建一个CRUD程序,并且我有一个很大的结构,要添加到MySQL数据库中的字段超过70个。

我想知道是否有一种方法可以自动将结构映射到我的数据库中,这样我就不必手动创建表,而只需复制我的结构?

2 个答案:

答案 0 :(得分:3)

我还没有找到一种完全自动化该过程的方法,但是您至少可以使用标签和少量代码来创建它们。

Workarround示例:

野外有一些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()

答案 1 :(得分:0)

尝试gen-model

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

完成