当前位置:网站首页>go : delete database data using grom
go : delete database data using grom
2022-07-30 08:03:00 【pedestrians have】
你受的苦 吃的亏 担的责 扛的罪 忍的痛 到最后都会变成光 照亮你的路 !!!
代码已放在:https://gitee.com/hjx_RuGuoYunZhiDao/strom-huang-go
可参照文档:https://learnku.com/docs/gorm/v2/create/9732#e9dfd9
1、 引入gorm
import (
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
2、链接数据库
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、model
//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 gorm.DeletedAt //表示软删除的标识
}
//指定数据库表名称
func (TUser) TableName() string {
return "t_user"
}
5、具体代码
package main
import (
"fmt"
"log"
"os"
model "strom-huang-go/go_mysql/model"
"time"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
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](localhost: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
}
//删除一条 DELETE FROM `t_user` WHERE `t_user`.`id` = 3
db.Delete(&model.TUser{
ID: 3})
//with extra parameters DELETE FROM `t_user` WHERE name = 'jinzhu' AND `t_user`.`id` = 3
db.Where("name = ?", "jinzhu").Delete(&model.TUser{
ID: 3})
// 根据主键删除 DELETE FROM `t_user` WHERE `t_user`.`id` = 3
db.Delete(&model.TUser{
}, 3)
//多个删除:相当于In : DELETE FROM `t_user` WHERE `t_user`.`id` IN (3,4,5)
db.Delete(&model.TUser{
}, []int{
3, 4, 5})
//批量删除 : DELETE FROM `t_user` WHERE nick_name like
db.Delete(&model.TUser{
}, "nick_name like ?", "%6666%")
// 和上面一个意思 DELETE FROM `t_user` WHERE phone like '%00000%'
db.Where("phone like ?", "%00000%").Delete(&model.TUser{
})
//-------------------------------------软删除------------------------------------------------
//Soft deletes are a bit special,如果你的model里面有delete_ator other identifiers,can be added on top:gorm.deletedat 来表述
//如果没有的话,Modified methods can be used:
//UPDATE `t_user` SET `deleted_at`='2022-05-13 11:51:48.981' WHERE `t_user`.`id` = 3 AND `t_user`.`deleted_at` IS NULL
db.Delete(&model.TUser{
ID: 3})
// 批量删除 UPDATE `t_user` SET `deleted_at`='2022-05-13 11:53:51.055' WHERE name = 20 AND `t_user`.`deleted_at` IS NULL
db.Where("name = ?", 20).Delete(&model.TUser{
})
// 在查询时会忽略被软删除的记录 SELECT * FROM `t_user` WHERE age = 20 AND `t_user`.`deleted_at` IS NULL
db.Where("age = 20").Find(&model.TUser{
})
}
边栏推荐
- 使用navicat连接mysql数据库时常报的错误:2003、1698、1251
- taro 打包编译报错
- MySQL master-slave replication configuration construction, one step in place
- Linx common directory & file management commands & VI editor usage introduction
- bean的生命周期
- Ali: How many methods are there for multi-threaded sequential operation?
- 架构设计指南 如何成为架构师
- The Society of Mind - Marvin Minsky
- 万能js时间日期格式转换
- Detailed explanation of numpy multidimensional array ndarray
猜你喜欢

Huawei released "ten inventions", including computing, intelligent driving and other new fields

Is it possible to use the same port for UDP and TCP?

C#的访问修饰符,声明修饰符,关键字有哪些?扫盲篇

RAID disk array

The Society of Mind - Marvin Minsky

golang : Zap日志整合

@Bean 与 @Component 用在同一个类上,会怎样?

Electron之初出茅庐——搭建环境并运行第一个程序

阿里二面:Redis有几种集群方案?我答了4种

Rodrigues: vector representation of rotation matrices
随机推荐
go : use gorm to modify data
入选“十大硬核科技”,详解可信密态计算(TECC)技术点
Electron使用romote报错 : Uncaught TypeError: Cannot read property ‘BrowserWindow‘ of undefined
上传文件--文件类型大全,图片类型,文档类型,视频类型,压缩包类型
什么是微服务?
相机坐标系,世界坐标系,像素坐标系三者转换,以及OPENGLDEFocal Length和Opengl 的 Fov转换
Linx common directory & file management commands & VI editor usage introduction
Playing script killing with AI: actually more involved than me
Station B collapsed, what would you do if you were the developer in charge that night?
Required request body is missing problem solving
Keil编译大小和存储说明
idea built-in translation plugin
How to use Swagger, say goodbye to postman
学生成绩管理系统(C语言)
Derivative Operations on Vectors and Derivative Operations on Vector Cross and Dot Products
Ali: How many methods are there for multi-threaded sequential operation?
(GGG)JWT
Is it possible to use the same port for UDP and TCP?
assert
golang : Zap日志整合