go-gorm
kingcwt2023-07-06前端golang
go笔记3
gorm CRUD
package mgorm
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
type Product struct {
gorm.Model
Code string
Price uint
}
// 创建表
func create(db *gorm.DB) {
db.AutoMigrate(&Product{})
}
// 创建一条记录
func insert(db *gorm.DB) {
p := Product{
Code: "1002",
Price: 500,
}
db.Create(&p)
}
// 查找一条记录
func find(db *gorm.DB) {
var p Product
// db.First(&p, 1) //id 1
db.First(&p, "code = ?", "1001") // 按字段查找
fmt.Printf("p: %v\n", p)
}
// update one
func updateOne(db *gorm.DB) {
var p Product
db.First(&p, "code = ?", "1001") // 查找 code 字段值为 D42 的记录
d := db.Model(&p).Update("Price", 1000)
fmt.Printf("d: %v\n", d)
}
func updateMany(db *gorm.DB) {
var p Product
db.First(&p, "code = ?", "1002") // 按字段查找
db.Model(&p).Updates(Product{Price: 2000, Code: "F42"})
}
// 删除 这里删除只是加个标记deleted_at 会有一个删除时间
func delete(db *gorm.DB) {
var p Product
db.Delete(&p, 1)
}
func TestMgormMain() {
dsn := "root:password@qq.com@tcp(127.0.0.1:3306)/golang_db?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
panic(err)
}
// find(db)
// insert(db)
delete(db)
}
package main
import (
"go3/mgorm"
"gorm.io/gorm"
)
type Product struct {
gorm.Model
Code string
Price uint
}
func main() {
mgorm.TestMgormMain()
}