In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article is a detailed introduction to "how to use xorm to operate mysql in Go". The content is detailed, the steps are clear, and the details are properly handled. I hope this article "how to use xorm to operate mysql in Go" can help you solve your doubts. Let's go deeper and learn new knowledge together with the ideas of Xiaobian.
xorm
Xorm is a simple and powerful Go ORM library.
It can make database operation very simple.
The goal of xorm is not to stop you from learning SQL altogether, we don't think SQL will be replaced by ORM, but ORM will solve most simple SQL needs.
Xorm supports a mix of the two styles.
Xorm also provides tools to generate structs according to the table structure of the database through the reverse command, eliminating the need for manual code organization, which is very convenient. Official address: xorm.io/
installation
Go to xorm's github address, we want to download 2 packages, github.com/go-xorm
1. xorm driver package, we use xorm core package 2. cmd toolkit, used to generate struct corresponding to data table using reverse command
Download 2 packages separately with the go get command
go get github.com/go-xorm/xorm``go get github.com/go-xorm/cmd/xorm
When the download is complete, the go-xorm package appears under the github.com folder
Generate data structure struct
The local database test has two data tables, doctor_tb and user_tb. The data structure is as follows:
我们现在就来生成这 2 张数据表的结构模型。
1、在任意项目下新建一个文件夹 xorm_models,文件名没有规定,为了存放生成的代码文件。
2、拷贝 cmd 工具包中的摸板目录到 xorm_models 下,在文件目录github.com\go-xorm\cmd\xorm\templates\goxorm下
config 是生成的配置信息,struct.go.tpl 是数据摸板,允许自定义,可以根据自己的项目需求,修改摸板。一般不需要修改。
3、打开 cmd 命令行窗口,进入 xorm_models 目录下,执行 reverse 命令:xorm reverse [数据库类型] [数据库连接串] [模板目录]xorm reverse mysql root:112233@tcp(127.0.0.1:3305)/test?charset=utf8 templates/goxorm
4、数据结构代码会自动生成在 xorm_models/models 目录下。
我们能看到生成了和表名同名的 2 个数据结构文件 doctor_tb.go 和 user_tb.go
package models import ( "time" ) type DoctorTb struct { Id int `xorm:"not null pk autoincr INT(11)"` Name string `xorm:"default '' comment('姓名') VARCHAR(50)"` Age int `xorm:"default 0 comment('年龄') INT(11)"` Sex int `xorm:"default 0 comment('性别') INT(11)"` Addtime time.Time `xorm:"DATETIME"` }使用 xorm
xorm 支持链式的写法
engine.Where("age > ?", 40).Or("name like ?", "林%").OrderBy("Id desc").Find(&docList2) 也支持直接执行 sql 语句engine.SQL("select * from doctor_tb where age > ?", 40).Find(&docList4)
附上增删改查事务的 demo 例子,代码里都有注释,很容易看懂。xorm 的封装比较友好,只要熟悉 sql 语句,即便不看文档,也能顺利的使用各种关键字。
package main import ( "fmt" _ "github.com/go-sql-driver/mysql" "github.com/go-xorm/xorm" "goShare/xorm_models/models" "time" ) func main() { var engine *xorm.Engine //连接数据库 engine, err := xorm.NewEngine("mysql", "root:112233@tcp(127.0.0.1:3305)/test?charset=utf8") if err != nil { fmt.Println(err) return } //连接测试 if err := engine.Ping(); err != nil { fmt.Println(err) return } defer engine.Close() //延迟关闭数据库 fmt.Println("数据库链接成功") //查询单条数据 var doc models.DoctorTb b, _ := engine.Where("name = ?", "钟南山").Get(&doc) if b { fmt.Println(doc) } else { fmt.Println("数据不存在") } //查询单条数据方式 2 会根据结构体的 doc2 := models.DoctorTb{Name: "钟南山"} b, _ = engine.Get(&doc2) fmt.Println(doc2) //新增数据 doc3 := models.DoctorTb{0, "王医生", 48, 1, time.Now()} i3, _ := engine.InsertOne(doc3) fmt.Println("新增结果:", i3) //查询列表 docList := make([]models.DoctorTb, 0) engine.Where("age > ? or name like ?", 40, "林%").Find(&docList) fmt.Println("docList:", docList) //查询列表方式 2 docList2 := make([]models.DoctorTb, 0) engine.Where("age > ?", 40).Or("name like ?", "林%").OrderBy("Id desc").Find(&docList2) fmt.Println("docList2:", docList2) //查询分页 docList3 := make([]models.DoctorTb, 0) page := 0 //页索引 pageSize := 2 //每页数据 limit := pageSize start := page * pageSize totalCount, err := engine.Where("age > ? or name like ?", 40, "林%").Limit(limit, start).FindAndCount(&docList3) fmt.Println("总记录数:", totalCount, "docList3:", docList3) //直接用语句查询 docList4 := make([]models.DoctorTb, 0) engine.SQL("select * from doctor_tb where age > ?", 40).Find(&docList4) fmt.Println("docList4:", docList4) //删除 docDel := models.DoctorTb{Name: "王医生"} iDel, _ := engine.Delete(&docDel) fmt.Println("删除结果:", iDel) //删除方式 2 engine.Exec("delete from doctor_tb where Id = ?", 3) //更新数据 doc5 := models.DoctorTb{Name: "钟医生"} //更新数据 ID 为 2 的记录名字更改为"钟医生" iUpdate, _ := engine.Id(2).Update(&doc5) fmt.Println("更新结果:", iUpdate) //指定表名查询。Table() user := models.UserTb{Id: 2} b, _ = engine.Table("user_tb").Get(&user) fmt.Println(user) //事务 session := engine.NewSession() defer session.Close() err = session.Begin() _, err = session.Exec("delete from doctor_tb where Id = ?", 6) if err != nil { session.Rollback() return } _, err = session.Exec("delete from user_tb where Id = ?", 10) if err != nil { session.Rollback() return } err = session.Commit() if err != nil { return } fmt.Println("事务执行成功") }读到这里,这篇"Go中如何使用xorm操作mysql"文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注行业资讯频道。
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.