goweb/global/mysql.go

37 lines
839 B
Go

package global
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"log"
"os"
"time"
)
// InitMySQLClient 初始化MySQL连接
func InitMySQLClient() {
USER := "casbin"
PASS := "casbin123"
HOST := "192.168.3.9"
PORT := "3306"
DBNAME := "casbin_demo"
newLogger := logger.New(
log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
logger.Config{
SlowThreshold: time.Second, // Slow SQL threshold
LogLevel: logger.Info, // Log level
Colorful: true, // Disable color
},
)
url := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", USER, PASS, HOST, PORT, DBNAME)
conn, err := gorm.Open(mysql.Open(url), &gorm.Config{Logger: newLogger})
if err != nil {
Log.Panicf("初始化MySQL连接失败, 错误信息: %v", err)
}
MySQLConn = conn
}