为了账号安全,请及时绑定邮箱和手机立即绑定

如何从 Go struct 生成 MySQL 表

如何从 Go struct 生成 MySQL 表

Go
翻翻过去那场雪 2023-06-12 15:46:34
我正在使用 Go 创建一个 CRUD 程序,我有一个相当大的结构,其中包含 70 多个字段,我想将它们添加到 MySQL 数据库中。我想知道是否有一种方法可以自动将结构映射到我的数据库中,这样我就不必手动创建表,它只会复制我的结构?
查看完整描述

2 回答

?
幕布斯6054654

TA贡献1876条经验 获得超7个赞

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

解决方法示例:

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


查看完整回答
反对 回复 2023-06-12
?
慕的地10843

TA贡献1785条经验 获得超8个赞

尝试生成模型

go get -u github.com/DaoYoung/gen-model

gen-model init # then set value in .gen-model.yaml

gen-model create

完毕


查看完整回答
反对 回复 2023-06-12
  • 2 回答
  • 0 关注
  • 79 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信