当前位置: 首页 > 工具软件 > go-db > 使用案例 >

golang 封装db文件

谭景明
2023-12-01

直接上代码

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 {
 类似资料: