You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

47 lines
1.3 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package common
import (
"fmt"
"github.com/spf13/viper"
"github.com/zggsong/gin-vue-demo/model"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
var DB *gorm.DB
func InitDB() *gorm.DB {
// 配置 MySQL 连接参数
username := viper.GetString("datasource.username") // 账号
password := viper.GetString("datasource.password") // 密码
host := viper.GetString("datasource.host") // 数据库地址可以是Ip或者域名
port := viper.GetInt64("datasource.port") // 数据库端口
database := viper.GetString("datasource.database") // 数据库名
charset := viper.GetString("datasource.charset") // 字符集
// 拼接下 dsn 参数, dsn 格式可以参考上面的语法,这里使用 Sprintf 动态拼接 dsn 参数,因为一般数据库连接参数,我们都是保存在配置文件里面,需要从配置文件加载参数,然后拼接 dsn。
dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=True&loc=Local",
username,
password,
host,
port,
database,
charset)
// 连接 Mysql, 获得 DB 类型实例,用于后面的数据库读写操作。
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
panic("连接数据库失败, error=" + err.Error())
}
db.AutoMigrate(&model.User{})
DB = db
return db
}
func GetDB() *gorm.DB {
return DB
}