# Day12 Gin框架之gorm

# 基本使用

  • 安装驱动
go get -u gorm.io/gorm
go get -u gorm.io/driver/mysql
  • 基本使用
package main

import (
	"fmt"
	"time"

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

type User struct {
	ID        uint64 `gorm:"primarykey"`
	Name      string `gorm:"index"`
	Age       int8   `gorm:"default:10"`
	CreatedAt time.Time
	UpdatedAt time.Time
	IsDeleted bool
}

func main() {
	dsn := "root:123456@tcp(127.0.0.1:3306)/go_mysql?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic("failed to connect database")
	}

	// 迁移 schema,users 复数
	db.AutoMigrate(&User{})

	// Create
	var u1 = User{
		ID:   2,
		Name: "linda",
		Age:  22,
	}
	db.Create(&u1)

	// Read
	var u User
	db.First(&u, 1) // 根据整型主键查找
	fmt.Printf("u:%#v\n", &u)

	db.First(&u, "name = ?", "linda1") // 查找 name 字段值为 linda 的记录
	fmt.Printf("u:%#v\n", &u)

	// Update - WHERE `id` = 2 条件只会解析主键 id
	db.Debug().Model(&User{ID: 2, Age: 100}).Update("Age", 18)
	db.Debug().Model(&u).Update("Age", 18)

	// Delete - 删除 User
	db.Delete(&User{}, 2)
}
上次更新: 12/12/2022, 8:55:46 PM