Preload
、Joins
的预加载go get -u gorm.io/gorm
go get -u gorm.io/driver/sqlite
快速入门
package main
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
const (
host = "xxx"
port = 8000
user = "username"
passwd = "xxx"
db = "topgoer_gorm"
other = "charset=utf8mb4&parseTime=True&loc=Local"
)
type Product struct {
gorm.Model
Code string
Price uint
}
func MyPrint(p interface{}) {
fmt.Printf("type: %T\tvalue: %v\n", p, p)
}
func main() {
dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?%s", user, passwd, host, port, db, other)
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
fmt.Println("conn mysql fail", err)
return
}
sqlDb, _ := db.DB()
defer sqlDb.Close() // 关闭链接
// 自动检查User结构是否发生变化,变化则进行迁移
db.AutoMigrate(&Product{})
// create
//db.Create(&Product{Code: "D42", Price: 100})
//db.Create(&Product{Code: "D43", Price: 200})
// read
var product Product
db.First(&product, 1) // 根据整型主键查找
MyPrint(product)
db.First(&product, "code = ?", "D43") // 查找code字段为D43的记录
MyPrint(product)
// update 更新单个字段
db.Model(&product).Update("price", 300) // 将product的price更新为300
MyPrint(product)
// updates 更新多个字段
db.Model(&product).Updates(Product{Code: "F43", Price: 400}) // 仅更新非零值字段
MyPrint(product)
db.Model(&product).Updates(map\[string\]interface{}{
"Code": "F44",
"Price": 500,
})
MyPrint(product)
// delete, 注意:此处必须是结构体指针,不能是结构体实例
db.Delete(new(Product), 1) // 删除product
}
手机扫一扫
移动阅读更方便
你可能感兴趣的文章