登录
首页 >  Golang >  Go问答

使用 Go 结构体创建 MySQL 数据表

来源:stackoverflow

时间:2024-03-15 10:54:25 244浏览 收藏

Golang小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《使用 Go 结构体创建 MySQL 数据表》带大家来了解一下##content_title##,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!


问题内容

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

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


解决方案


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

解决方法示例:

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

尝试gen-model

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

完成

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《使用 Go 结构体创建 MySQL 数据表》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>