当前位置:网站首页>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)
}
边栏推荐
- Graphical relational database design ideas, this is too vivid
- CTO说不建议我使用SELECT * ,这是为什么?
- Advanced multi-threading (CountDownLatch, deadlock, thread-safe collection class)
- Let the "label" content in Baidu map generator expand--solution
- DHCP principle and configuration
- Equation Derivation Proof of Vector Triple Product
- Test the basics 02
- 华为发布“十大发明”,包含计算、智能驾驶等新领域
- Test Development Engineer Growth Diary 001 - Some Introduction to Agile Testing, CI/CD/CT, DecOps
- 上传文件--文件类型大全,图片类型,文档类型,视频类型,压缩包类型
猜你喜欢

Test development engineer growth diary 016 - those things about the test

Test Development Engineer Growth Diary 001 - Some Introduction to Agile Testing, CI/CD/CT, DecOps

AI元学习引入神经科学,医疗效果有望精准提升

(GGG)JWT

Ali two sides: List several tips for Api interface optimization

你被MySQL 中的反斜杠 \\坑过吗?

【MySQL】MySQL中如何实现分页操作

STL源码剖析:迭代器的概念理解,以及代码测试。

The Society of Mind - Marvin Minsky

MySQL master-slave replication configuration construction, one step in place
随机推荐
Rodrigues: vector representation of rotation matrices
Test Development Engineer Growth Diary 001 - Some Introduction to Agile Testing, CI/CD/CT, DecOps
Detailed explanation of numpy multidimensional array ndarray
DNS domain name resolution services
Upload file -- file type, picture type, document type, video type, compressed package type
Derivative Operations on Vectors and Derivative Operations on Vector Cross and Dot Products
DHCP原理与配置
(GGG)JWT
万能js时间日期格式转换
什么是微服务?
Test Development Engineer Growth Diary 010 - CI/CD/CT in Jenkins (Continuous Integration Build/Continuous Delivery/Continuous Testing)
idea内置翻译插件
bean的生命周期
你被MySQL 中的反斜杠 \\坑过吗?
DNS域名解析服务
矩阵的行列式的计算及其源码
node.js中实现对数据库的链式操作
2020 数学建模之旅
Mobile phone side scroll to page to specify location
RAID disk array