赞
踩
GORM 是 Go 语言的一个对象关系映射(ORM)库,它提供了一种简单、简洁的方式来与数据库交互,通过让开发人员使用 Go 结构体来代替直接编写 SQL 查询。
GORM 支持多个数据库后端,例如 MySQL、PostgreSQL、SQLite 和 SQL Server,并提供自动表创建、模式迁移以及数据库表之间的关联等功能。
使用 GORM,开发人员可以将模型定义为 Go 结构体,并使用 Create、Save、Update 和 Delete 等方法来与数据库交互。GORM 还提供了查询构建器接口,允许开发人员使用流畅的语法编写复杂的查询。
官方文档:https://gorm.io/zh_CN/
go get -u gorm.io/gorm
go get -u gorm.io/driver/mysql
package main
import (
"fmt"
"time"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
CreatedAT time.Time `created_at`
}
func (User) TableName() string {
return "users"
}
var db *gorm.DB
func init() {
dsn := "root:123456@tcp(127.0.0.1:3306)/blogok?charset=utf8mb4&parseTime=True&loc=Local"
d, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
fmt.Println("open mysql failed,", err)
}
db = d
sqlDB, _ := db.DB()
sqlDB.SetMaxIdleConns(10)
sqlDB.SetMaxOpenConns(500)
sqlDB.SetConnMaxLifetime(time.Hour)
}
func main() {
var user User
db.Debug().First(&user)
fmt.Printf("user: %v\n", user)
}
以下是一个简单的 GORM 模型定义示例:
type User struct {//表名
ID int `json:"id"`//列名
Name string `json:"name"`
Email string `json:"email"`
CreatedAT time.Time `created_at`
}
//自定义表名
func (User) TableName() string {
return "users"
}
//获取第一条记录,按主键排序
db.First(&user)
SELECT * FROM `user` ORDER BY `user`.`id` LIMIT 1
//根据主键ID查找
db.First(&user, 10)
SELECT * FROM `user` WHERE `user`.`id` = 10 ORDER BY `user`.`id` LIMIT 1
//查找name等于张三的用户
db.First(&user, "name=?", "张三")
SELECT * FROM `user` WHERE name='张三' ORDER BY `user`.`id` LIMIT 1
// 获取所有记录
db.Find(&user);
select * from user;
db.Select("name", "email").Find(&user)
SELECT `name`,`email` FROM `users`
//或者
db.Select([]string{"name", "email"}).Find(&user)
SELECT `name`,`email` FROM `users`
// 获取第一个匹配记录
db.Where("name=?","张三").First(&user);
SELECT * FROM `users` WHERE name='张三' ORDER BY `users`.`id` LIMIT 1
//或者
db.Where(&User{Name:"张三"}).First(&user);
SELECT * FROM `users` WHERE `users`.`name` = '张三' ORDER BY `users`.`id` LIMIT 1
// 获取所有匹配记录
db.Where("name=?","张三").Find(&user);
SELECT * FROM `users` WHERE name='张三'
//不等于
db.Where("name<>?","张三").Find(&user);
//in
db.Where("name in (?) ",[]string{"张三","李四"}).Find(&user)
//like
db.Where("name like ?","%张三%").Find(&user);
//and
db.Where("name =? and mail=?","张三","abc@mail.com").Find(&user);
// not条件查询
db.Not("name", "张三").First(&user)
SELECT * FROM `users` WHERE `name` <> '张三' ORDER BY `users`.`id` LIMIT 1
// Not In
db.Not("name", []string{"张三", "李四"}).Find(&user)
SELECT * FROM `users` WHERE `name` NOT IN ('张三','李四')
db.Not([]int64{4, 5, 6}).First(&user)
SELECT * FROM `users` WHERE `users`.`id` NOT IN (4,5,6) ORDER BY `users`.`id` LIMIT 1
db.Where("name=?", "张三").Or("email=?", "abc@mail.com").Find(&user)
SELECT * FROM `users` WHERE name='张三' OR email='abc@mail.com'
db.Where(User{Name: "张三"}).Or(User{Email: "abc@mail.com"}).Find(&user)
SELECT * FROM `users` WHERE `users`.`name` = '张三' OR `users`.`email` = 'abc@mail.com'
db.Where("name =?", "张三").Where("email=? ", "abc@mail.com").Find(&user)
SELECT * FROM `users` WHERE name ='张三' AND email='abc@mail.com'
db.Debug().Order("id desc").Find(&user)
SELECT * FROM `users` ORDER BY id desc
db.Limit(10).Find(&user)
SELECT * FROM `users` LIMIT 10
指定跳过的记录数
db.Offset(3).Find(&user);
var count int64
db.Debug().Find(&user).Count(&count)
SELECT count(*) FROM `users`
db.Preload("Orders").Find(&user)
SELECT * FROM user;
SELECT * FROM orders WHERE user_id IN (1,2,3);
db.Model(&User).Where("name","张三").Update("name","李四");
db.Model(&User).Updates(User{Name:"张三",Email:"abc@mail.com"})
db.Create(&User{Name: "张三", Email: "abc@mail.com", CreatedAT: time.Now()})
INSERT INTO `users` (`name`,`email`,`created_at`) VALUES ('张三','abc@mail.com','2022-10-19 11:05:05.826')
如果模型有DeletedAt
字段,将自动获得软删除功能! 在调用Delete时不会从数据库中永久删除,而是只将字段DeletedAt的值设置为当前时间。软删除的记录将在查询时被忽略。
//根据主键ID删除
db.Delete(&user, 1)
DELETE FROM `users` WHERE `users`.`id` = 1
db.Where("name like ?", "%李四%").Delete(User{})
DELETE FROM `users` WHERE name like '%李四%'
db.Debug().Delete(User{}, "name like ?", "%李四%")
DELETE FROM `users` WHERE name like '%李四%'
//使用Unscoped查找软删除的记录
db.Unscoped().Where("name=?","张三").Find(&user);
// 使用Unscoped永久删除记录
db.Unscoped().Delete(&user);
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。