当前位置: 首页 > 工具软件 > Gor Go > 使用案例 >

go-gorm

经清野
2023-12-01
package main

import (
	"encoding/json"
	"fmt"
	"time"

	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
)

var MainDB *gorm.DB

func main() {
	url := "test:123456@tcp(127.0.0.1:3306)/blogger?charset=utf8mb4&parseTime=True&loc=Local"
	MainDB, err := InitMySQL(url, true, 10, 10)
	if err != nil {
		fmt.Println("initDB err:", err)
		return
	}
	var tb Category
	db := MainDB
	db.Select("category_name").Where(map[string]interface{}{"category_no": 1}).First(&tb)
	if db.Error == gorm.ErrRecordNotFound {
		fmt.Println("没有记录")
	} else {
		fmt.Println(tb)
	}

	var name Name
	MainDB.Table("category").Select("category_name").Where(map[string]interface{}{"category_no": 1}).First(&name)
	fmt.Println(name, "name", MainDB.Error)

	cName := ""
	row := MainDB.Table("category").Select("category_name").Where(map[string]interface{}{"category_no": 9}).Row()  // 查询一行数据
	err = row.Scan(&cName)
	fmt.Println(err, cName, "cname")
}

type Name struct {
	Name string `gorm:"column:category_name"`
	Hh   int    `gorm:"column:hhh"`
}

type Msg struct {
	Name string `json:"mz"`
	Age  int    `json:"age"`
}

func byteToStruct() {
	jsonStr := `{"name":"hh",     "age":1 }`
	var msg Msg
	err := json.Unmarshal([]byte(jsonStr), &msg)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(msg)
}

func InitMySQL(dbURL string, showLog bool, maxOpenConns, maxIdleConns int) (*gorm.DB, error) {
	db, err := gorm.Open("mysql", dbURL)
	db.DB().SetMaxOpenConns(maxOpenConns)
	db.DB().SetMaxIdleConns(maxIdleConns)
	db.LogMode(showLog)

	return db, err
}

type Category struct {
	ID           uint32    `json:"id" gorm:"primary_key" comment:"自增主键"`
	CategoryName string    `json:"category_name" gorm:"type:varchar(255);not null" comment:"名称"`
	CategoryNo   uint32    `json:"category_no" gorm:"type:int(10);not null" comment:"分类排序"`
	CreateTime   time.Time `json:"create_time" gorm:"type:timestamp" comment:"创建时间"`
	UpdateTime   time.Time `json:"update_time" gorm:"type:timestamp;allow null" comment:"更新时间"`
}

// 设置表名
func (c Category) TableName() string {
	return "category"
}

 类似资料: