2025-01-14 13:09:25 +08:00
|
|
|
|
package db
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"fmt"
|
|
|
|
|
"gorm.io/driver/mysql"
|
|
|
|
|
"gorm.io/gorm"
|
2025-01-15 10:21:51 +08:00
|
|
|
|
"youtu_ecpm/pkg/config"
|
2025-01-14 13:09:25 +08:00
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
var Db *gorm.DB
|
|
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
|
//配置MySQL连接参数
|
2025-01-15 10:21:51 +08:00
|
|
|
|
dsn := fmt.Sprintf(
|
|
|
|
|
"%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local",
|
|
|
|
|
config.GetDBUserName(), //账号
|
|
|
|
|
config.GetDBPassword(), //密码
|
|
|
|
|
config.GetDBHost(), //数据库地址,可以是Ip或者域名
|
|
|
|
|
config.GetDBPort(), //数据库端口
|
|
|
|
|
config.GetDBName(), //数据库名
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
//创建数据库连接
|
2025-01-14 13:09:25 +08:00
|
|
|
|
db, err := gorm.Open(mysql.Open(dsn))
|
|
|
|
|
if err != nil {
|
|
|
|
|
panic("连接数据库失败, error=" + err.Error())
|
|
|
|
|
}
|
|
|
|
|
Db = db
|
|
|
|
|
}
|