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.

41 lines
998 B

2 years ago
package common
2 years ago
import (
"errors"
"expenses/model"
"fmt"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
var DB *gorm.DB
2 years ago
func InitDB(conf model.DataSource) (*gorm.DB, error) {
// 拼接下 dsn 参数, dsn 格式可以参考上面的语法
//这里使用 Sprintf 动态拼接 dsn 参数,因为一般数据库连接参数,我们都是保存在配置文件里面,需要从配置文件加载参数,然后拼接 dsn。
2 years ago
dsn := fmt.Sprintf("host=%v user=%v password=%v dbname=%v port=%v sslmode=disable TimeZone=Asia/Shanghai",
2 years ago
conf.Host,
conf.Username,
conf.Password,
conf.Database,
conf.Port)
// 连接 Postgresql, 获得 DB 类型实例,用于后面的数据库读写操作。
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
return nil, errors.New(fmt.Sprintf("连接数据库失败 " + err.Error()))
}
err = db.AutoMigrate(&model.User{})
if err != nil {
return nil, err
}
DB = db
2 years ago
return db, nil
}
func GetDB() *gorm.DB {
return DB
}