

golang gorm 操作mysql
source link: https://studygolang.com/articles/16301?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

golang 官方的那个操作mysql的有点麻烦所以就使用了gorm,下面就gorm的使用做下简单介绍
下载gorm:
go get -u github.com/jinzhu/gorm
在项目中引入gorm:
import ( "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" )
定义db连接信息
func DbConn(MyUser, Password, Host, Db string, Port int) *gorm.DB { connArgs := fmt.Sprintf("%s:%s@(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local", MyUser,Password, Host, Port, Db ) db, err := gorm.Open("mysql", connArgs) if err != nil { log.Fatal(err) } db.SingularTable(true) return db }
由于grom是使用的orm映射,所以需要定义要操作的表的model,在go中需要定义一个struct, struct的名字就是对应数据库中的表名,注意gorm查找struct名对应数据库中的表名的时候会默认把你的struct中的大写字母转换为小写并加上“s”,所以可以加上 db.SingularTable(true)
让grom转义struct名字的时候不用加上s。我是提前在数据库中创建好表的然后再用grom去查询的,也可以用gorm去创建表,我感觉还是直接在数据库上创建,修改表字段的操作方便,grom只用来查询和更新数据。
假设数据库中的表已经创建好,下面是数据库中的建表语句:
CREATE TABLE `xz_auto_server_conf` ( `id` int(11) NOT NULL AUTO_INCREMENT, `group_zone` varchar(32) NOT NULL COMMENT '大区例如:wanba,changan,aiweiyou,360', `server_id` int(11) DEFAULT '0' COMMENT '区服id', `server_name` varchar(255) NOT NULL COMMENT '区服名称', `open_time` varchar(64) DEFAULT NULL COMMENT '开服时间', `service` varchar(30) DEFAULT NULL COMMENT '环境,test测试服,formal混服,wb玩吧', `username` varchar(100) DEFAULT NULL COMMENT 'data管理员名称', `submit_date` datetime DEFAULT NULL COMMENT '记录提交时间', `status` tinyint(2) DEFAULT '0' COMMENT '状态,0未处理,1已处理,默认为0', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
定义model,即struct, 定于struct时我们可以只定义我们需要从数据库中取回的特定字段:
gorm在转义表名的时候会把stuct的大写字母(首字母除外) 替换成“_”,所以下面的"XzAutoServerConf "会转义成数数据库中对应“xz_auto_server conf”的表名, 对应的字段名的查找会先按照tag里面的名称去里面查找,如果没有定义标签则按照struct定义的字段查找,查找的时候struct字段中的大写会被转义成“ ”,例“GroupZone”会去查找表中的group_zone字段
//定义struct type XzAutoServerConf struct { GroupZone string `gorm:"column:group_zone"` ServerId int OpenTime string ServerName string Status int } //定义数据库连接 type ConnInfo struct { MyUser string Password string Host string Port int Db string } func main () { cn := ConnInfo{ "root", 123456", "127.0.0.1", 3306, "xd_data", } db := DbConn(cn.MyUser,cn.Password,cn.Host,cn.Db,cn.Port) defer db.Close() // 关闭数据库链接,defer会在函数结束时关闭数据库连接 var rows []api.XzAutoServerConf //select db.Where("status=?", 0).Select([]string{"group_zone", "server_id", "open_time", "server_name"}).Find(&rows) //update err := db.Model(&rows).Where("server_id=?", 80).Update("status", 1).Error if err !=nil { fmt.Println(err) } fmt.Println(rows) }
更多grom操作可以参考: https://jasperxu.github.io/gorm-zh/
Recommend
-
234
jinzhu/gorm: GORM V1, V2 moved to https://github.com/go-gorm/gorm...
-
41
前言 对于golang中使用gorm操作mysql,可能其他的操作都是固定的,唯一麻烦的就是字段的映射。 gorm允许自己定义一个表的结构映射,但是,golang中,首字母大写来表示public或者private,而gorm在做映射的时候,大写...
-
29
gorm是go语言的一个orm框架,框架的原理和思想在这里就不做详细介绍了,我主要演示一下gorm的实际使用。 开启mysql连接 主要用到 gorm.open()这个方法 //参数含义:数据库用户名、密码、主...
-
8
The fantastic ORM library for Golang, aims to be developer friendly. Overview Full-Featured ORM Associations (Has One, Has Many, Belongs To, Many To Many, Polymorphism, Single-table inheritance) Hooks (B...
-
7
golang gorm mysql 读写时间戳 eflight · 2天之前 · 100 次点击 · 预计阅读时间 2 分钟 · 大...
-
5
<?xml encoding="utf-8" ??>Introduction This guide explains how to build an example web API in Go to create, update, delete book records from a database. At the end of this article, you should be...
-
9
V2EX › 程序员 Golang gorm 怎么跨库查询 MySQL? gejigeji · 1 天前 · 1096 次...
-
5
Simple paging with Golang templates and GORM Published: Jul 14, 2020 / Last modified: Jul 15, 2020 Go code: const PageCount = 10 type P...
-
7
golang gorm框架的sql注入漏洞 keluda · 2020-06-27 18:32:50 · 6153 次点击 · 预计阅读时间 1 分钟 · 大约8小时之前 开始浏览
-
11
【笔记】Go 语言通过 Gorm 操作 Sqlite 数据库 捕捉一只爱折腾的绯鞠 ...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK