使用 Go 结构体创建 MySQL 数据表
时间:2024-03-15
浏览:244
作者:佚名
Golang小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《使用 Go 结构体创建 MySQL 数据表》带大家来了解一下##content_title##,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!
问题内容
我正在使用 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.
}
当您拥有该部分时,您可以像下面的示例一样创建表(也来自 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()
go get -u github.com/DaoYoung/gen-model gen-model init # then set value in .gen-model.yaml gen-model create
完成
文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《使用 Go 结构体创建 MySQL 数据表》文章吧,也可关注golang学习网公众号了解相关技术文章。
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.27
热门专题
