Gorm 基本使用 | 青训营笔记

150 阅读2分钟

这是我参与「第五届青训营」伴学笔记创作活动的第 6 天

简介

Gorm 是一个 Go 语言的 ORM (Object-Relational Mapping) 框架,使得开发人员可以使用 Go 的结构体来操作数据库。

Gorm 支持多种数据库,包括 MySQL、PostgreSQL、SQLite 和 SQL Server。它提供了一组高级功能,如自动迁移、预加载、关联关系、事务等。

使用

连接数据库

我们可以使用gorm.Open 连接数据库

func Init() {
   db, err := gorm.Open(mysql.Open("user:pwd@tcp(localhost)/dbname?charset=utf8mb4"))
   if err != nil {
       panic(err)
   }
}

同时 gorm 也提供了类似 mysql连接池的效果, 我们可以设置其 最大连接数, 最大空闲数,最大生命周期等

    sqlDb, err := db.DB()
    sqlDb.SetMaxOpenConns(m.MaxOpen)
    sqlDb.SetMaxIdleConns(m.MaxIdle)
    sqlDb.SetConnMaxLifetime(time.Duration(m.MaxLifetime) * time.Second)

声明结构体

我们可以假设有一个 users 表, 其对应的结构体应为

type User struct {
    ID int `gorm:"primary_key,auto_increment,column:id"`
    Username string `gorm:"unique"`
    Password string
}

我们可以使用 gorm tag 来为其设置 主键,自动递增 等

自动同步

有时候我们可能需要自动同步表结构,可以使用 db.AutoMigrate() 来实现

db.AutoMigrate(&User{})

此时,如果数据库中不存在 users (gorm 自动使用结构体名称的蛇形复数作为表名称) 表时将会自动创建。

我们也可以通过 Tablename 重写默认表名

func (User) TableName() string {
  return "accounts"
}

CURD

func main() {
    // Insert
    db.Create(&User{
        Username: "xcsoft",
        Password: "xcsoft.pwd"
    })
    // Update
    db.Model(&User{}).Where(&User{Username: "xcsoft"}).Updates(&User{Password: "pwd2"})
    // Delete
    db.Where(&User{Username: "xcsoft"}).Delete(&User{})
    // Select
    db.Model(&User{}).Select("username").Where(&User{ID: 1})
}

值得注意的是,当我们新增一条用户数据的时候,并不需要指定ID,因为我们已经将其ID设定为 auto_increment

插件支持

Gorm 同时还支持很多插件, 可以在 github.com/go-gorm/ 中找到

如: 乐观锁, 读写分离 等插件

context 支持

对于长 sql 查询,我们可以使用 context 设置超时时间

ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel()  db.WithContext(ctx).Find(&users) 

安全

默认情况下, Gorm 已经对使用sql进行了转译,从而避免注入问题。

同时我们仍然需要在业务上不信任用户的任何输入,应使用正则白名单waf 等机制对其进行过滤。

结语

Gorm 是 Golang 下一个较为完善的 Orm. 他为我们提供了一个十分方便的途径对 数据库进行操作。