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.
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/zggsong/gin-vue-demo/model"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
var DB * gorm . DB
func init ( ) {
// 配置 MySQL 连接参数
username := "root" // 账号
password := "jiaobaba" // 密码
host := "127.0.0.1" // 数据库地址, 可以是Ip或者域名
port := 3306 // 数据库端口
Dbname := "gin-vue-demo" // 数据库名
timeout := "10s" // 连接超时, 10秒
// 拼接下 dsn 参数, dsn 格式可以参考上面的语法,这里使用 Sprintf 动态拼接 dsn 参数,因为一般数据库连接参数,我们都是保存在配置文件里面,需要从配置文件加载参数,然后拼接 dsn。
dsn := fmt . Sprintf ( "%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local&timeout=%s" ,
username ,
password ,
host ,
port ,
Dbname ,
timeout )
// 连接 Mysql, 获得 DB 类型实例,用于后面的数据库读写操作。
db , err := gorm . Open ( mysql . Open ( dsn ) , & gorm . Config { } )
if err != nil {
panic ( "连接数据库失败, error=" + err . Error ( ) )
}
db . AutoMigrate ( & model . User { } )
DB = db
}
func GetDB ( ) * gorm . DB {
return DB
}