Skip to content

gorm

时间跟踪

自定义

go
type Base struct {
	CreateTime  time.Time `gorm:"column:create_time;default:now();autoCreateTime" json:"createTime"`
	UpdateTime  time.Time `gorm:"column:update_time;default:now();autoUpdateTime" json:"updateTime"`
}

type Base struct {
	CreateTime  time.Time `gorm:"column:create_time;default:CURRENT_TIMESTAMP;autoCreateTime" json:"createTime"`
	UpdateTime  time.Time `gorm:"column:update_time;default:CURRENT_TIMESTAMP;autoUpdateTime" json:"updateTime"`
}

默认

go
type Base struct {
	Id          uint64    `gorm:"column:id;primaryKey;autoIncrement;not null;comment:POC自增编号" json:"id"`
	CreatedAt   time.Time
	UpdatedAt   time.Time
}

gorm 链接

go
package pool

import (
	"fmt"
	"time"

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

func ConnectPoolMySQL() *gorm.DB {
	dsn := "root:@tcp(10.0.35.75:4000)/la_tidb?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		fmt.Println(err)
	}

	// 获取通用数据库对象 sql.DB ,然后使用其提供的功能
	sqlDB, _ := db.DB()

	// SetMaxIdleConns 用于设置连接池中空闲连接的最大数量。
	sqlDB.SetMaxIdleConns(10)

	// SetMaxOpenConns 设置打开数据库连接的最大数量。
	sqlDB.SetMaxOpenConns(100)

	// SetConnMaxLifetime 设置了连接可复用的最大时间。
	sqlDB.SetConnMaxLifetime(time.Hour)

	return db
}

func ConnectPoolPostgreSQL() *gorm.DB {
	dsn := "host=10.0.35.77 user=postgres password=postgres dbname=testa port=5432 sslmode=disable TimeZone=Asia/Shanghai"
	db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})

	if err != nil {
		fmt.Println(err)
	}

	// 获取通用数据库对象 sql.DB ,然后使用其提供的功能
	sqlDB, _ := db.DB()

	// SetMaxIdleConns 用于设置连接池中空闲连接的最大数量。
	sqlDB.SetMaxIdleConns(10)

	// SetMaxOpenConns 设置打开数据库连接的最大数量。
	sqlDB.SetMaxOpenConns(100)

	// SetConnMaxLifetime 设置了连接可复用的最大时间。
	sqlDB.SetConnMaxLifetime(time.Hour)

	return db
}

func ConnectPoolPostgreSQLAms() *gorm.DB {
	dsn := "host=10.0.35.77 user=postgres password=postgres dbname=testb port=5432 sslmode=disable TimeZone=Asia/Shanghai"
	dbAms, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})

	if err != nil {
		fmt.Println(err)
	}

	// 获取通用数据库对象 sql.DB ,然后使用其提供的功能
	sqlDB, _ := dbAms.DB()

	// SetMaxIdleConns 用于设置连接池中空闲连接的最大数量。
	sqlDB.SetMaxIdleConns(10)

	// SetMaxOpenConns 设置打开数据库连接的最大数量。
	sqlDB.SetMaxOpenConns(100)

	// SetConnMaxLifetime 设置了连接可复用的最大时间。
	sqlDB.SetConnMaxLifetime(time.Hour)

	return dbAms
}