Gorm 增删改查 (crud)

package main

import (
    "fmt"
    "gorm.io/driver/mysql"
    "gorm.io/gorm"
    "gorm.io/gorm/logger"
    "log"
    "os"
    "time"
)

type User struct {
    Id        int64
    Name      string
    Age       int32
    Email     string
    IsDeleted int8
}

var db *gorm.DB

func init() {
    dsn := "root:123456@tcp(127.0.0.1:3306)/test?charset=utf8mb4&parseTime=True&loc=Local"

    newLogger := logger.New(log.New(os.Stdout, "\r\n", log.LstdFlags),
        logger.Config{
            SlowThreshold:             time.Second,
            Colorful:                  true,
            IgnoreRecordNotFoundError: false,
            ParameterizedQueries:      true,
            LogLevel:                  logger.Info,
        })

    // 全局sql log设置
    DB, err := gorm.Open(mysql.Open(dsn), &gorm.Config{Logger: newLogger})
    if err != nil {
        fmt.Printf("mysql连接失败 %s\n", err)
        return
    }
    db = DB
}

// 条件分页查询
func GetPage(name string, pageNo, pageSize int64) []User {
    var users []User
    tx := db.Table("user").Select("id", "name", "age", "email").Offset(int((pageNo - 1) * pageSize)).Limit(int(pageSize))
    if name != "" {
        tx.Where("name like CONCAT('%', ?, '%')", name)
    }
    tx.Find(&users)
    return users
}

// 查询单个
func GetOne(id int64) (User, error) {
    var user User
    db.Table("user").Select("id", "name", "age", "email").Where("id = ?", id).First(&user)
    return user, nil
}

// 查询多个
func GetList() ([]User, error) {
    var users []User
    db.Table("user").Select("id", "name", "age", "email").Limit(10).Find(&users)
    return users, nil
}

// 新增
func InsertOne(user User) error {
    db.Table("user").Create(&user)
    return nil
}

// 批量插入
func BatchInsert(users []User) error {
    //db.Table("user").Create(&users)
    db.Table("user").CreateInBatches(&users, 100)
    return nil
}

// 单个删除
func DeleteOne(id int64, name string) error {
    db.Table("user").Where("id = ? and name = ?", id, name).Delete(&User{})
    return nil
}

func DeleteByName(name string) error {
    db.Table("user").Where("name = ?", name).Delete(&User{})
    return nil
}

// update one
func UpdateOne(id int64, name string) error {
    db.Table("user").Where("id = ?", id).Update("name", name)
    return nil
}

// 批量更新
func Updates(id1, id2 int64, name string) error {
    db.Table("user").Where("id in ?", []int64{id1, id2}).Updates(User{Name: name})
    return nil
}

func main() {
}
// 官方文档 https://gorm.io/zh_CN/docs/

 

posted @ 2023-05-22 11:11  文所未闻  阅读(75)  评论(0编辑  收藏  举报