go的gorm操作涉及增删改查

2022-07-10 13:25:07 浏览数 (2)

代码语言:txt复制
package main

import (
	"fmt"
	"math/rand"
	"strconv"
	"time"

	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
)

type City struct {
	CityId        int64  `gorm:"column:city_id"`
	CityName      string `gorm: "column:city_name"`
	CityIntroduce string `gorm:"column:city_introduce"`
}

func main() {
	db := initDB()
	defer db.Close()
	var id int64 = 2222

	//查
	var a_city City
	db.Table("city").Where("city_id=?", id).First(&a_city)
	fmt.Println("%#T", a_city)
	if a_city.CityId == 0 {
		//增
		city1 := City{CityId: id, CityName: "paris", CityIntroduce: "good city"}
		db.Table("city").Create(&city1)
	}
	//改
	random_data := strconv.Itoa(rand.Int())
	new_city_introduce := "good city:"   random_data
	db.Table("city").Where("city_id=?", id).Update("city_introduce", new_city_introduce)
	//删
	db.Table("city").Where("city_id=?", id).Delete(&City{})

}

func initDB() *gorm.DB {
	dsn := "root:123456@tcp(127.0.0.1:3306)/test?charset=utf8mb4"
	db, err := gorm.Open("mysql", dsn)
	if err != nil {
		panic(err)
	}
	db.DB().SetMaxOpenConns(50)
	db.DB().SetMaxIdleConns(2)
	db.DB().SetConnMaxLifetime(time.Second * 300)
	if err = db.DB().Ping(); err != nil {
		panic(err)
	}
	return db
}

0 人点赞