go orm GORM

官网:https://gorm.io/

docs:https://gorm.io/docs/

博客:https://www.tizi365.com/archives/6.html

Go 复制代码
import (
    "fmt"

    "gorm.io/driver/mysql"
    "gorm.io/gorm"
)

type Product struct {
    gorm.Model
    Code  string
    Price uint
}

func main() {
    fmt.Println("main ...")

    dsn := "act:Q***wsx@tcp(127.0.0.1:3306)/tbname1?charset=utf8mb4&parseTime=True&loc=Local"
    var db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
    if err != nil {
       panic("failed to connect database")
    }

    // Migrate the schema
    db.AutoMigrate(&Product{})

    // Create
    db.Create(&Product{Code: "D4211", Price: 100})

    // Read
    var product Product
    db.First(&product, 1)                 // find product with integer primary key
    db.First(&product, "code = ?", "D42") // find product with code D42
    fmt.Println(product)

    // Update - update product's price to 200
    db.Model(&product).Update("Price", 200)
    // Update - update multiple fields
    db.Model(&product).Updates(Product{Price: 200, Code: "F42"}) // non-zero fields
    db.Model(&product).Updates(map[string]interface{}{"Price": 200, "Code": "F42"})

    // Delete - delete product
    db.Delete(&product, 1)

    fmt.Println("success ...")
}
相关推荐
峥无6 分钟前
C++11 深度详解:现代 C++ 基石全梳理
开发语言·c++·笔记
阿米亚波17 分钟前
【C++ STL】std::unordered_multimap
开发语言·数据结构·c++·笔记·stl
名字还没想好☜34 分钟前
Go 的 time.After 在 select 循环里内存泄漏:定时器堆积原理与 timer.Reset 正确姿势
java·数据库·golang·go·goroutine
SomeB1oody1 小时前
【RustyML入门】1.0. 快速上手
开发语言·后端·机器学习·rust·教程
狗凯之家源码网1 小时前
短剧系统搭建实战:源码功能与商业变现效果全景展示
开发语言·php
史呆芬1 小时前
分布式事务实战:微服务跨服务数据一致性解决方案
java·后端·spring cloud
犀利豆2 小时前
Claude code tools 研究系列(二)EnterPlanMode
人工智能·后端
用户69371750013842 小时前
AI时代,程序员该往哪走?
前端·后端