当前位置:网站首页>go : use gorm to modify data
go : use gorm to modify data
2022-07-30 08:03:00 【pedestrians have】
can make you regret,It was never something you did,It's what you want to do but don't do!!!
代码已放在: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 Do not update this field 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)
}
边栏推荐
- STL源码剖析:bound friend template friend代码测试和理解
- Proof of distance calculation from space vertex to plane and its source code
- 你被MySQL 中的反斜杠 \\坑过吗?
- 空间直线到平面上的交点的计算证明及其源码
- New material under the plastic restriction order - polylactic acid (PLA)
- node.js中实现对数据库的链式操作
- 从 Google 离职,前Go 语言负责人跳槽小公司
- 向量叉乘的几何意义及其模的计算
- 手机端滚动至页面指定位置
- The usage of window.open(), js opens a new form
猜你喜欢

STL源码剖析:class template explicit specialization代码测试和理解

Calculate the inverse source of the matrix (using the adjoint matrix, a 3x3 matrix)

Rodrigues: vector representation of rotation matrices

Universal js time date format conversion

What are the access modifiers, declaration modifiers, and keywords in C#?Literacy articles

UDP和TCP使用同一个端口,可行吗?
![[GO语言基础] 一.为什么我要学习Golang以及GO语言入门普及](/img/ac/80ab67505f7df52d92a206bc3dd50e.png)
[GO语言基础] 一.为什么我要学习Golang以及GO语言入门普及

The Society of Mind - Marvin Minsky

“AI教练”请进家,家庭智能健身蓬勃发展

From catching up to surpassing, domestic software shows its talents
随机推荐
向量的导数运算和向量叉乘以及点乘的导数运算
What new materials are used in the large aircraft C919?
golang : Zap日志整合
go : 使用 grom 删除数据库数据
理解和熟悉递归中的尝试
Required request body is missing problem solving
千万级数据量的表,怎样最快速度查询?
ArrayList
ETL为什么经常变成ELT甚至LET?
手机端滚动至页面指定位置
Universal js time date format conversion
No, the Log4j vulnerability hasn't been fully fixed yet?
Rodrigues: vector representation of rotation matrices
Table with tens of millions of data, how to query the fastest?
Redis 如何实现防止超卖和库存扣减操作?
Mobile phone side scroll to page to specify location
Ali two sides: List several tips for Api interface optimization
[GO语言基础] 一.为什么我要学习Golang以及GO语言入门普及
这个终端连接工具,碾压Xshell
华为发布“十大发明”,包含计算、智能驾驶等新领域