0
点赞
收藏
分享

微信扫一扫

零基础Go语言从入门到精通(数据库编程:02-Gorm 操作 MySQL 数据库)

鱼满舱 2022-06-27 阅读 47


Gorm 介绍

The fantastic ORM library for Golang Go 语言的 超棒的 ORM 类库

功能强大:

  • 全功能ORM(几乎)
  • 关联(包含一个,包含多个,属于,多对多,多种包含)
  • Callbacks(创建/保存/更新/删除/查找之前/之后)
  • 预加载(急加载)
  • 事务
  • 复合主键
  • SQL Builder
  • 自动迁移
  • 日志
  • 可扩展,编写基于GORM回调的插件
  • 每个功能都有测试
  • 开发人员友好

操作 MySQL 数据库

加载驱动

操作mysql需要 mysql 的驱动,由于我使用 go mod 来管理依赖,直接导入包就行。

import (
_ "github.com/go-sql-driver/mysql"
)

导入 gorm 包

方法同上,导入包即可。

import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)

打开数据库

调用 gorm.Open 方法打开数据库

// 创建mysql连接
func Init() {
DB, err = gorm.Open("mysql", "user:password@/ginsql?charset=utf8&parseTime=True&loc=Local")
if err != nil {
panic(nil)
}
// 自动迁移模式
// 解决中文乱码问题
DB.Set("gorm:table_options", "ENGINE=InnoDB DEFAULT CHARSET=utf8").AutoMigrate(&AccountInfo{})
}

建表

建表一般采用 数据模型同步的方式,先创建一个 model

// 定义数据模型
type AccountInfo struct {
gorm.Model
Name string `gorm:"not null;unique"`
Password string `gorm:"not null;"`
Status uint `gorm:"default:0"`
}

我们登录mysql客户端,查看生成的表结构

封装ORM接口

// ORM 封装接口
type AccountInfoAPI struct{}
func (h *AccountInfoAPI) List(offset, limit int) (accountInfos []AccountInfo) {
DB.Offset(offset).Limit(limit).Find(&accountInfos)
return
}
func (h *AccountInfoAPI) Create(accountInfo *AccountInfo) error {
err := DB.Create(accountInfo).Error
return err
}
func (h *AccountInfoAPI) Get(id int) (accountInfo AccountInfo) {
DB.Find(&accountInfo, id)
return
}
func (h *AccountInfoAPI) Update(id int, updates *AccountInfo) error {
accountInfo := &AccountInfo{}
err := DB.Where("id = ?", id).First(&accountInfo).Error
if err != nil {
return err
}
err = DB.Model(&accountInfo).Updates(updates).Error
return err
}
func (h *AccountInfoAPI) Delete(id int) error {
var accountInfo AccountInfo
err := DB.First(&accountInfo, id).Error
if err != nil {
return err
}
err = DB.Delete(&accountInfo).Error
return err
}


func (h *AccountInfoAPI) Count() (int, error) {
var count int
var accountInfo AccountInfo
// 软删除数据不要
err := DB.Model(&accountInfo).Where("deleted_at is null").Count(&count).Error
if err != nil {
return count, err
}
return count, err
}

增删改查

通过gin框架搭建web服务,来增加

创建记录

// gin路由注册函数

func addHandler(ctx *gin.Context) {

    var accountInfo sql.AccountInfo

    if err := ctx.ShouldBindJSON(&accountInfo); err != nil {

        ctx.JSON(http.StatusBadRequest, gin.H{

            "msg": err,

        })

        return

    }

    if err := api.Create(&accountInfo); err != nil {

        ctx.JSON(http.StatusBadRequest, gin.H{

            "msg": err,

        })

        return

    }

    ctx.JSON(http.StatusOK, gin.H{

        "msg":  "success",

        "data": accountInfo,

    })

}

下面我们postman来操作增加信息

执行发送后返回结果

我们在增加一条数据

查看mysql中的表数据

查询list

func listHandler(ctx *gin.Context) {

    offset, limit := 0, 10

// 获取url中参数

    queryOffset := ctx.Query("offset")

    if queryOffset != "" {

// 字符串专为int类型函数

        offset, _ = strconv.Atoi(queryOffset)

    }

    queryLimit := ctx.Query("limit")

    if queryLimit != "" {

        limit, _ = strconv.Atoi(queryLimit)

    }

    ctx.JSON(http.StatusOK, gin.H{

        "msg":  "success",

        "data": api.List(offset, limit),

    })

}

​​http://localhost:8080/list?offset=0&limit=2​​

更新

这里介绍按照一条数据id进行数据更新

  • 更新前记录
  • 执行更新操作
  • 更新后的结果

删除

查看数据库(这里是采用软删除:一般公司中核心数据都不能轻而易举删除掉的)

目的:需要对数据进行可查,把删除的状态给变更掉。

2.5.5 count

使用 count 查询(gin 注册的函数)

func countHandler(ctx *gin.Context) {

    count, err := api.Count()

    if err != nil {

        ctx.JSON(http.StatusOK, gin.H{

            "msg": err.Error(),

        })

    }

    ctx.JSON(http.StatusOK, gin.H{

        "msg":  "success",

        "data": count,

    })

}

通过postman方式的演示如下

gorm快速浏览

​​Count in GORM - Learn Programming with Real Apps​​


举报

相关推荐

0 条评论