Golang gorm 快速开始保存查询单条数据查询全部数据
Posted 知其黑、受其白
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Golang gorm 快速开始保存查询单条数据查询全部数据相关的知识,希望对你有一定的参考价值。
阅读目录
概览
一个神奇的,对开发人员友好的 Golang ORM 库。
参考文档:https://gorm.io/zh_CN/docs/
https://github.com/go-gorm/gorm
1. 概览
- 全特性 ORM (几乎包含所有特性)
- 模型关联 (一对一, 一对多,一对多(反向), 多对多, 多态关联)
- 钩子 (
Before/After Create/Save/Update/Delete/Find
) - 预加载
- 事务
- 复合主键
- SQL 构造器
- 自动迁移
- 日志
- 基于GORM回调编写可扩展插件
- 全特性测试覆盖
- 开发者友好
2. 安装 mysql、gorm、gin 包
官网采用 sqlite 库,我们采用 MySQL 库。
// 安装 MySQL 驱动
go get -u gorm.io/driver/mysql
// 安装 gorm 包
go get -u gorm.io/gorm
// 安装gin
go get -u github.com/gin-gonic/gin
PS E:\\go_test> go get -u gorm.io/driver/mysql
go: downloading gorm.io/driver/mysql v1.4.5
go: downloading gorm.io/gorm v1.23.8
go: downloading gorm.io/gorm v1.24.3
go: downloading github.com/jinzhu/now v1.1.5
go: upgraded github.com/jinzhu/now v1.0.1 => v1.1.5
go: added gorm.io/driver/mysql v1.4.5
go: added gorm.io/gorm v1.24.3
PS E:\\go_test>
PS E:\\go_test> go get -u gorm.io/gorm
go: downloading gorm.io/gorm v1.24.3
go: downloading github.com/jinzhu/inflection v1.0.0
go: downloading github.com/jinzhu/now v1.1.5
PS E:\\go_test>
PS E:\\go_test> go get -u github.com/gin-gonic/gin
go: downloading github.com/gin-gonic/gin v1.8.2
go: downloading github.com/gin-contrib/sse v0.1.0
go: downloading github.com/mattn/go-isatty v0.0.16
go: downloading golang.org/x/net v0.4.0
go: downloading github.com/go-playground/validator/v10 v10.11.1
go: downloading github.com/pelletier/go-toml/v2 v2.0.6
go: downloading github.com/ugorji/go/codec v1.2.7
go: downloading google.golang.org/protobuf v1.28.1
go: downloading gopkg.in/yaml.v2 v2.4.0
go: downloading github.com/mattn/go-isatty v0.0.17
go: downloading github.com/goccy/go-json v0.9.11
go: downloading github.com/ugorji/go v1.2.8
go: downloading github.com/ugorji/go/codec v1.2.8
go: downloading github.com/json-iterator/go v1.1.12
go: downloading github.com/pelletier/go-toml v1.9.5
go: downloading github.com/go-playground/validator v9.31.0+incompatible
go: downloading golang.org/x/sys v0.3.0
go: downloading github.com/go-playground/universal-translator v0.18.0
go: downloading github.com/goccy/go-json v0.10.0
go: downloading golang.org/x/net v0.5.0
go: downloading github.com/leodido/go-urn v1.2.1
go: downloading golang.org/x/crypto v0.0.0-20211215153901-e495a2d5b3d3
go: downloading golang.org/x/text v0.5.0
go: downloading github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421
go: downloading github.com/modern-go/reflect2 v1.0.2
go: downloading github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd
go: downloading golang.org/x/sys v0.4.0
go: downloading github.com/go-playground/locales v0.14.0
go: downloading golang.org/x/crypto v0.5.0
go: downloading golang.org/x/text v0.6.0
go: downloading github.com/go-playground/locales v0.14.1
go: added github.com/gin-contrib/sse v0.1.0
go: added github.com/gin-gonic/gin v1.8.2
go: added github.com/go-playground/locales v0.14.1
go: added github.com/go-playground/universal-translator v0.18.0
go: added github.com/go-playground/validator/v10 v10.11.1
go: added github.com/goccy/go-json v0.10.0
go: added github.com/json-iterator/go v1.1.12
go: added github.com/leodido/go-urn v1.2.1
go: added github.com/mattn/go-isatty v0.0.17
go: added github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd
go: added github.com/modern-go/reflect2 v1.0.2
go: added github.com/pelletier/go-toml/v2 v2.0.6
go: added github.com/ugorji/go/codec v1.2.8
go: upgraded golang.org/x/crypto v0.0.0-20191205180655-e7c4368fe9dd => v0.5.0
go: upgraded golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e => v0.5.0
go: upgraded golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd => v0.4.0
go: upgraded golang.org/x/text v0.3.0 => v0.6.0
go: added google.golang.org/protobuf v1.28.1
go: added gopkg.in/yaml.v2 v2.4.0
PS E:\\go_test>
快速开始
1. 创建项目目录
PS E:\\> mkdir gormlearn
PS E:\\gormlearn> go work init
PS E:\\gormlearn> mkdir gormtest
PS E:\\gormlearn> cd .\\gormtest\\
PS E:\\gormlearn\\gormtest> go mod init test.com/gormtest
go: creating new go.mod: module test.com/gormtest
PS E:\\gormlearn\\gormtest> cd ..
PS E:\\gormlearn>
PS E:\\gormlearn> go work use ./gormtest
目录结构
$ tree -C
.gormlearn
|-- go.work
`-- gormtest
|-- go.mod
|-- main.go
2、新建数据库表
CREATE TABLE `users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增ID',
`username` varchar(30) NOT NULL COMMENT '账号',
`password` varchar(100) NOT NULL COMMENT '密码',
`createtime` bigint(20) NOT NULL DEFAULT 0 COMMENT '创建时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
3、创建目录及文件
3.1、E:\\gormlearn\\gormtest\\main.go
package main
import (
"log"
"github.com/gin-gonic/gin"
"test.com/gormtest/router"
)
func main()
r := gin.Default()
router.InitRouter(r)
err := r.Run(":8888")
if err != nil
log.Fatalln(err)
3.2、E:\\gormlearn\\gormtest\\router\\router.go
package router
import (
"github.com/gin-gonic/gin"
"test.com/gormtest/api"
)
func InitRouter(r *gin.Engine)
api.RegisterRouter(r)
3.3、E:\\gormlearn\\gormtest\\api\\router.go
package api
import "github.com/gin-gonic/gin"
func RegisterRouter(r *gin.Engine)
r.GET("/save", SaveUser)
r.GET("/get", GetUser)
r.GET("/getall", GetAll)
3.4、E:\\gormlearn\\gormtest\\api\\user.go
package api
import (
"time"
"github.com/gin-gonic/gin"
"test.com/gormtest/model"
)
// 新增
func SaveUser(c *gin.Context)
user := &model.User
Username: "zhangsan",
Password: "123e4r5",
CreateTime: time.Now().UnixMilli(),
model.SaveUser(user)
c.JSON(200, user)
// 查询单条
func GetUser(c *gin.Context)
user := model.GetById(1)
c.JSON(200, user)
// 查询全部
func GetAll(c *gin.Context)
user := model.GetAll()
c.JSON(200, user)
3.5、E:\\gormlearn\\gormtest\\model\\user.go
package model
import "log"
/*
定义User模型,绑定users表,ORM库操作数据库,
需要定义一个struct类型和MYSQL表进行绑定或者叫映射,
struct字段和MYSQL表字段一一对应
*/
type User struct
ID int64 // 主键
//通过在字段后面的标签说明,定义golang字段和表字段的关系
//例如 `gorm:"column:username"` 标签说明含义是: Mysql表的列名(字段名)为username
Username string `gorm:"column:username"`
Password string `gorm:"column:password"`
//创建时间,时间戳
CreateTime int64 `gorm:"column:createtime"`
// 设置表名
func (u User) TableName() string
return "users"
func SaveUser(user *User)
// 数据库的操作,连接数据库
err := DB.Create(user).Error
if err != nil
log.Println("insert user error:", err)
// 查询单条
func GetById(id int64) User
var user User
err := DB.Where("id=?", id).First(&user)
if err != nil
log.Println("get user by id error:", err)
return user
// 查询全部
func GetAll() []User
var user []User
err := DB.Find(&user).Error
if err != nil
log.Println("get user by id error:", err)
return user
3.6、E:\\gormlearn\\gormtest\\model\\gorm.go
package model
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
var DB *gorm.DB
func init()
// 连接数据库
//配置MySQL连接参数
username := "root" //账号
password := "" //密码
host := "127.0.0.1" //数据库地址,可以是Ip或者域名
port := 3306 //数据库端口
Dbname := "test" //数据库名
dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local", username, password, host, port, Dbname)
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config
Logger: logger.Default.LogMode(logger.Info),
)
if err != nil
panic("连接数据库失败, error=" + err.Error())
DB = db
预览效果
以上是关于Golang gorm 快速开始保存查询单条数据查询全部数据的主要内容,如果未能解决你的问题,请参考以下文章