Mysql - Gorm的使用:增删改查

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package main
 
import (
    "fmt"
    "gorm.io/driver/mysql"
    "gorm.io/gorm"
)
 
type Product struct {
    gorm.Model
    Code  string
    Price uint
}
 
func main() {
    dsn := "root:root@tcp(127.0.0.1:3306)/test_lc"
    db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
    if err != nil {
        fmt.Println(err)
    }
    // //创建表
    db.AutoMigrate(&Product{})
    p := Product{
        Price: 200,
        Code:  "2",
    }
    //插入数据
    db.Create(&p)
    //查看数据
    var product Product
    db.First(&product, 1)
    fmt.Printf("product: %v\n", product)
 
    //改
    //这里有坑,修改单个字段使用的是update 修改多个使用到的是updates
    db.Model(&product).Update("Price", 300)
    //更新多个字段
    db.Model(&product).Updates(Product{Price:300,Code:"3"})
    db.Model(&product).Updates(map[string]interface{}{"Price": 300, "Code": "3"})
    //删
    db.Delete(&product, 1)  //误区:err = global.GVA_DB.Delete(&channel).Where("channel_id = ?", channel.ChannelId).Error
}

  

gorm 模型 model

gorm的模型更多的是一种约定,而不是配置,gorm.Model是grom的一种结构体代表的是

1
2
3
4
5
6
type Model struct{
  ID        uint           `gorm:"primaryKey"`
  CreatedAt time.Time
  UpdatedAt time.Time
  DeletedAt gorm.DeletedAt `gorm:"index"`
}

  

posted @   李若盛开  阅读(19)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
点击右上角即可分享
微信分享提示