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

gin-gorm-api-example/main.go at master · cgrant/gin-gorm-api-example · GitHubicon-default.png?t=M3K6https://github.com/cgrant/gin-gorm-api-example/blob/master/main.go

  1. Gorm 介绍

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

功能强大:

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

2. 操作 MySQL 数据库

2.1 加载驱动

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

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

2.2 导入 gorm 包

方法同上,导入包即可。

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

2.3 打开数据库

调用 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{})
}

2.4 建表

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

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

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

2.5 封装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
}

2.6 增删改查

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

2.6.1 创建记录

// 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中的表数据

2.6.2 查询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

2.6.3 更新

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

  • 更新前记录

  • 执行更新操作

  • 更新后的结果

2.6.4 删除

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

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

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方式的演示如下

2.6.5 gorm快速浏览

Count in GORM - Learn Programming with Real Apps

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

艾文教编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值