当前位置:网站首页>go : 使用gorm修改数据
go : 使用gorm修改数据
2022-07-30 05:51:00 【行人已】
能够让你后悔的,从来不是你做过的事,而是你想做却没有去做的事!!!
代码已放在: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,
})
3、修改数据
// 条件更新 UPDATE `t_user` SET `name`='aa',`updated_at`='2022-05-13 10:19:57.743' WHERE name = 'a'
db.Model(&model.TUser{
}).Where("name = ?", "a").Update("name", "aa")
//根据ID更新 UPDATE `t_user` SET `name`='test',`updated_at`='2022-05-13 10:27:49.548' WHERE `id` = 1
var user = model.TUser{
ID: 1}
db.Model(&user).Update("name", "test")
4、全部代码
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](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
}
// 条件更新 UPDATE `t_user` SET `name`='aa',`updated_at`='2022-05-13 10:19:57.743' WHERE name = 'a'
db.Model(&model.TUser{
}).Where("name = ?", "a").Update("name", "aa")
//根据ID更新 UPDATE `t_user` SET `name`='test',`updated_at`='2022-05-13 10:27:49.548' WHERE `id` = 1
var user = model.TUser{
ID: 1}
db.Model(&user).Update("name", "test")
//--------------------------------------更新多列---------------------------------------------
// 根据 `struct` 更新属性,只会更新非零值的字段
// UPDATE `t_user` SET `id`=1,`name`='hello',`password`='1',`phone`='123',`updated_at`='2022-05-13 10:32:17.812'
db.Model(&model.TUser{
ID: 1}).Updates(model.TUser{
Name: "hello", Password: "1", Phone: "123"})
// 根据 `map` 更新属性
// UPDATE `t_user` SET `password`='111',`phone`='456',`name`='hello',`updated_at`='2022-05-13 10:35:09.953' WHERE `id` = 1
db.Model(&model.TUser{
ID: 1}).Updates(map[string]interface{
}{
"name": "hello", "Password": "111", "Phone": "456"})
//--------------------------------------更新选定字段--------------------------------------
//忽略某些字段:UPDATE `t_user` SET `name`='hello',`updated_at`='2022-05-13 10:38:56.004' WHERE `id` = 1
db.Model(&model.TUser{
ID: 1}).Select("name").Updates(map[string]interface{
}{
"name": "hello", "Password": "111", "Phone": "456"})
//onmit 不更新这个字段 UPDATE `t_user` SET `password`='111',`phone`='456',`updated_at`='2022-05-13 10:39:57.516' WHERE `id` = 1
db.Model(&model.TUser{
ID: 1}).Omit("name").Updates(map[string]interface{
}{
"name": "hello", "Password": "111", "Phone": "456"})
//--------------------------------------批量更新--------------------------------------
// 根据 struct 更新
//UPDATE `t_user` SET `name`='hello',`created_at`='2022-05-13 10:45:11.233',`updated_at`='2022-05-13 10:45:11.255' WHERE phone = '122222'
db.Model(&model.TUser{
}).Where("phone = ?", "122222").Updates(&model.TUser{
Name: "hello", CreatedAt: time.Now()})
// 根据 map 更新 UPDATE `t_user` SET `name`='hello',`password`='1213' WHERE id IN (1,2)
db.Table("t_user").Where("id IN ?", []int{
1, 2}).Updates(map[string]interface{
}{
"name": "hello", "password": "1213"})
//更新的记录数
result := db.Model(model.TUser{
}).Where("phone = ?", "122222").Updates(model.TUser{
Name: "hello", Password: "1213"})
fmt.Print(result.RowsAffected)
}
边栏推荐
猜你喜欢

The terminal connection tools, rolling Xshell

Ali two sides: Sentinel vs Hystrix comparison, how to choose?

STL source code analysis: conceptual understanding of iterators, and code testing.

The introduction of AI meta-learning into neuroscience, the medical effect is expected to improve accurately

The calculation and source code of the straight line intersecting the space plane

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

Vue项目通过node连接MySQL数据库并实现增删改查操作

华为发布“十大发明”,包含计算、智能驾驶等新领域

Let the "label" content in Baidu map generator expand--solution

MYSQL下载及安装完整教程
随机推荐
PXE efficient mass network capacity
The calculation and source code of the straight line intersecting the space plane
What new materials are used in the large aircraft C919?
No, the Log4j vulnerability hasn't been fully fixed yet?
VR机器人教你如何正确打乒乓球
Playing script killing with AI: actually more involved than me
The CTO said I was not advised to use SELECT *, why is that?
LVM和磁盘配额
debian 问题
idea built-in translation plugin
Rodrigues:旋转矩阵的向量表达
node.js中实现对数据库的链式操作
export , export default, import complete usage
分布式系统中的开创者—莱斯利·兰伯特
Multithreading basics (multithreaded memory, security, communication, thread pools and blocking queues)
B站崩了,如果是你是那晚负责的开发人员你会怎么做?
搭建vsftpd服务并实现本地用户访问
Oracle查看表空间使用率及爆满解决方案
New material under the plastic restriction order - polylactic acid (PLA)
千万级数据量的表,怎样最快速度查询?