

介绍一个超好用的orm库gorm【Golang 入门系列十二】
source link: https://studygolang.com/articles/33020
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.

介绍一个超好用的orm库gorm【Golang 入门系列十二】
mb5fe94b3e552d9 · 大约10小时之前 · 24 次点击 · 预计阅读时间 2 分钟 · 不到1分钟之前 开始浏览之前在已经介绍了用的github.com/go-sql-driver/mysql 访问数据库,不太了解的可以看看之前的文章 https://www.cnblogs.com/zhangweizhong/category/1275863.html。
实际上,为提高开发效率,一般都会使用一些orm框架,把数据库层屏蔽,用户看到的只有对象而无需我们手动做一些转换,这样在使用的时候就非常方便。这种操作方式基本上已经成了标准做法。golang也有很多优秀的orm框架,今天就来介绍介绍gorm。
Gorm的功能
hook机制(Before/After Create/Save/Update/Delete/Find)
对象关系Has One, Has Many, Belongs To, Many To Many, Polymorphism
支持原生sql操作
链式api
支持的数据库有:mysql、postgre、sqlite、sqlserver
以上是gorm的功能,至于为什么是gorm?gorm 跟其他框架有什么不一样?这里就不在介绍了。直接讲用法吧。
go get -u github.com/jinzhu/gorm
数据库连接
db, err = gorm.Open("mysql", "root:root@tcp(127.0.0.1:3306)/irisapp?charset=utf8&parseTime=True&loc=Local")if err != nil { panic("连接数据库失败")}
连接比较简单,直接调用 gorm.Open 传入数据库地址即可。gorm支持基本上所有主流的关系数据库,只是连接方式上略有不同,这里我用的 mysql为例吧。
type Product struct { ID int `gorm:"primary_key"` Code string `gorm:"type:varchar(20);"` Price int `gorm:"type:int;"` Name string `gorm:"type:varchar(64);"` Mail string `gorm:"type:varchar(256);"` CreatedAt time.Time}
if !db.HasTable(&Like{}) { if err := db.Set("gorm:table_options", "ENGINE=InnoDB DEFAULT CHARSET=utf8").CreateTable(&Product{}).Error; err != nil { panic(err) }}
直接通过 db.CreateTable 就可以创建表了,非常方便,还可以通过 db.Set 设置一些额外的表属性
另外,还有自动同步创建表的方法:
// 自动迁移模式db.AutoMigrate(&Product{})
var product Productdb.First(&product, 1) // 查询id为1的productdb.First(&product, "code = ?", "ik01001") // 查询code为l1212的product
// 创建db.Create(&Product{Code: "ik01001", Price: 1000})
构造已给对象,直接调用 db.Create() 就可以插入一条记录。不用拼接sql语句,是不是很方便。
// 更新 - 更新product的price为2000db.Model(&product).Update("Price", 2000)
简单对象删除:
db.Delete(&product)复杂条件的删除:if err := db.Where(&Product{ID: 1}).Delete(Product{}).Error; err != nil { return err}
func CreateProducts(db *gorm.DB) err {
tx := db.Begin()
// 注意,一旦你在一个事务中,使用tx作为数据库句柄
if err := tx.Create(&Product{Code: "ik01003", Price: 3000}).Error; err != nil {
tx.Rollback()
return err
}
tx.Commit()
return nil
}
事务的处理也很简单,用 db.Begin() 声明开启事务,结束的时候调用 tx.Commit(),异常的时候调用 tx.Rollback()
1. 以上就把基本的增删改查介绍完了,实际使用中还有很多高级的用法,比如关联查询,主外键设置等。大家可以看看官方的使用说明:http://gorm.book.jasperxu.com/
有疑问加站长微信联系(非本文作者)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:1006366459
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK