直接上代码
package global
import (
"fmt"
"log"
"os"
"time"
"github.com/spf13/viper"
"gorm.io/driver/mysql"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"gorm.io/gorm/schema"
"shop.serv/utils"
)
var db *gorm.DB
// DB 通用数据库
func DB() *gorm.DB {
return db
}
func init() {
db = Conn(Config.Connections)
}
// Conn 连接数据库
func Conn(cfg Connections) *gorm.DB {
newLogger := logger.New(
log.New(os.Stdout, "\n", log.LstdFlags),
logger.Config{
SlowThreshold: time.Second,
LogLevel: logger.Error,
},
)
var dsn string
var dialector gorm.Dialector
if cfg.Driver == "mysql" {
dsn = fmt.Sprintf("%s:%s@(%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
cfg.Username, cfg.Password, cfg.Hostname, cfg.Database)
dialector = mysql.Open(dsn)
} else {
dsn = fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=5432 sslmode=disable TimeZone=Asia/Shanghai",
cfg.Hostname, cfg.Username, cfg.Password, cfg.Database)
dialector = postgres.Open(dsn)
}
db, err := gorm.Open(dialector, &gorm.Config{
Logger: newLogger,
NamingStrategy: schema.NamingStrategy{TablePrefix: cfg.Prefix, SingularTable: true},
SkipDefaultTransaction: true,
})
if err != nil {
log.Fatalln(err)
return nil
}
if Config.Debug {
db = db.Debug()
}
sql, err := db.DB()
if err == nil {
sql.SetConnMaxLifetime(time.Duration(time.Second * 86400))
}
return db
}
封装完成,在其他地方直接调用就好了
比如:
var user []User
global.DB().Where("1=1").FInd(&user)