我正在使用 Go 创建一个 CRUD 程序,我有一个很大的结构,其中包含 70 多个字段,我想将其添加到 MySQL 数据库中。
我想知道是否有一种方法可以将结构自动映射到我的数据库中,这样我就不必手动创建表,它只会复制我的结构?
我还没有找到一种方法来完全自动化该过程,但至少您可以使用标签和少量代码来创建它们。
有一些 github 项目可以帮助你实现这一目标。
例如可构造的
您必须向结构成员添加标签。
来自 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.
}
Run Code Online (Sandbox Code Playgroud)
当您拥有该部分后,您可以像下面的示例一样创建表(也来自 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()
Run Code Online (Sandbox Code Playgroud)