当前位置:网站首页>go : 使用gorm查询记录
go : 使用gorm查询记录
2022-07-30 05:51:00 【行人已】
生活本沉闷 跑起来才有风
具体代码已放在:https://gitee.com/hjx_RuGuoYunZhiDao/strom-huang-go/blob/master/go_mysql/db_grom_select.go
官方中文文档地址:https://learnku.com/docs/gorm/v2/query/9733
1、 引入gorm
import (
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
2、添加一个model
type TUser struct {
ID uint `gorm:"primaryKey"`
Name string
Password string
Phone string `gorm:"phone"`
NickName string `gorm:"nick_name"`
CreatedAt time.Time `gorm:"column:created_at;type:datetime"`
UpdatedAt time.Time `gorm:"column:updated_at;type:datetime"`
DeletedAt time.Time `gorm:"column:deleted_at;type:datetime"`
}
3、链接数据库
dsn := "root:[email protected](localhost:3306)/go_test?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
Logger: newLogger,
})
4、普通查询
var user01 = TUser{
}
db.First(&user01)
fmt.Printf("S: %#v\n", user01)
5、具体代码
package main
import (
"fmt"
"log"
"os"
"time"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
//model:
type TUser struct {
ID uint `gorm:"primaryKey"`
Name string
Password string
Phone string `gorm:"phone"`
NickName string `gorm:"nick_name"`
CreatedAt time.Time `gorm:"column:created_at;type:datetime"`
UpdatedAt time.Time `gorm:"column:updated_at;type:datetime"`
DeletedAt time.Time `gorm:"column:deleted_at;type:datetime"`
}
//指定数据库表名称
func (TUser) TableName() string {
return "t_user"
}
func main() {
//启用打印日志
newLogger := logger.New(
log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
logger.Config{
SlowThreshold: time.Second, // 慢 SQL 阈值
LogLevel: logger.Info, // Log level: Silent、Error、Warn、Info
Colorful: false, // 禁用彩色打印
},
)
dsn := "root:[email protected](127.0.0.1:3306)/go_admin?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
Logger: newLogger,
})
if err != nil {
fmt.Println(err)
return
}
//获取第一条
var user01 = TUser{
}
db.First(&user01)
fmt.Printf("S: %#v\n", user01)
// 获取一条记录,没有指定排序字段
var user02 = TUser{
}
db.Take(&user02)
fmt.Printf("S: %#v\n", user02)
//获取最后一条
var user03 = TUser{
}
db.Last(&user03)
fmt.Println(user03)
//获取第一条匹配的记录
var user04 = TUser{
}
result01 := db.Where("name", "xx").First(&user04)
fmt.Println(result01.RowsAffected)
//或者这样写
db.Find(&user04, "name", "xx")
fmt.Println("或者这样写:", result01.RowsAffected)
// 获取全部匹配的记录
var user05 = TUser{
}
result02 := db.Where("name <> ?", "r").First(&user05)
fmt.Println(result02.RowsAffected)
//in
var user06 = TUser{
}
db.Where("name IN ?", []string{
"r", "r 2"}).Find(&user06)
//like
db.Where("name like ?", "%aa%").Find(&user06)
//and
db.Where("name =? and phone =?", "r", "12345").Find(&user06)
//time
db.Where("created_at >?", "2022-05-12").Find(&user06)
// BETWEEN
db.Where("created_at BETWEEN ? AND ?", "lastWeek", "today").Find(&user06)
//Struct--查询,用model来匹配参数
db.Where(&TUser{
Name: "r", Phone: "123"}).Find(&user06)
// Map ----查询,用json的方式来匹配参数
db.Where(map[string]interface{
}{
"name": "r", "phone": "123"}).Find(&user06)
//-------------------------------------------------------------------or---------------------------------
db.Where("name", "r").Or("phone", "123").Find(&user06)
db.Where("name", "r").Or(&TUser{
Phone: "123", NickName: "x"}).Find(&user06)
//------------------------------------------------------------------order--------------------------
db.Order("id desc").Find(&user06)
//多个order
db.Order("id desc,created_at asc").Find(&user06)
//---------------------------------------------------------------Limit & Offse--------------
db.Limit(1).Find(&user06)
db.Offset(1).Find(&user06)
//分页操作
var PageNum = 1
var PageSize = 10
db.Limit(PageSize).Offset((PageNum - 1) * PageSize).Find(&user06)
}
边栏推荐
- From catching up to surpassing, domestic software shows its talents
- 头条二面:MySQL中有几种常见的 SQL 错误用法?
- Let the "label" content in Baidu map generator expand--solution
- 华为发布“十大发明”,包含计算、智能驾驶等新领域
- Go语学习笔记 - gorm使用 - 数据库配置、表新增 Web框架Gin(七)
- Local Implicit Grid Representations for 3D Scenes详解
- 2020 数学建模之旅
- B站崩了,如果是你是那晚负责的开发人员你会怎么做?
- Graphical relational database design ideas, this is too vivid
- ETL为什么经常变成ELT甚至LET?
猜你喜欢

STL源码剖析:临时对象的代码测试和理解

Bull: remove common characters

New material under the plastic restriction order - polylactic acid (PLA)

空间顶点到平面的距离计算的证明及其源码

What happens when @Bean and @Component are used on the same class?

相机坐标系,世界坐标系,像素坐标系三者转换,以及OPENGLDEFocal Length和Opengl 的 Fov转换

The Society of Mind - Marvin Minsky

2020年度总结——品曾经,明得失,展未来

这个终端连接工具,碾压Xshell

Graphical relational database design ideas, this is too vivid
随机推荐
首届人工智能安全大赛正式启动
华为发布“十大发明”,包含计算、智能驾驶等新领域
STL源码剖析:临时对象的代码测试和理解
Station B collapsed, what would you do if you were the developer in charge that night?
Ali Ermian: How many cluster solutions does Redis have?I answered 4
AI can identify race from X-rays, but no one knows why
The calculation and source code of the straight line intersecting the space plane
proftpd 配置文件说明
Test Development Engineer Growth Diary 001 - Some Introduction to Agile Testing, CI/CD/CT, DecOps
Test the basics 02
你被MySQL 中的反斜杠 \\坑过吗?
Go 使用 freecache 缓存
UDP和TCP使用同一个端口,可行吗?
RAID disk array
How to understand plucker coordinates (geometric understanding)
Bull: remove common characters
Table with tens of millions of data, how to query the fastest?
Derivative Operations on Vectors and Derivative Operations on Vector Cross and Dot Products
Rodrigues:旋转矩阵的向量表达
Rodrigues: vector representation of rotation matrices