如何从 Go struct 生成 MySQL 表

我正在使用 Go 创建一个 CRUD 程序,我有一个相当大的结构,其中包含 70 多个字段,我想将它们添加到 MySQL 数据库中。

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


翻翻过去那场雪
浏览 83回答 2
2回答

幕布斯6054654

我还没有找到完全自动化该过程的方法,但至少您可以使用标签和少量代码创建它们。解决方法示例:在野外有一些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.}当你有那个部分时,你可以像下面的例子一样创建表(也来自 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()

慕的地10843

尝试生成模型go get -u github.com/DaoYoung/gen-modelgen-model init # then set value in .gen-model.yamlgen-model create完毕
打开App,查看更多内容
随时随地看视频慕课网APP