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.
34 lines
930 B
34 lines
930 B
2 years ago
|
package db
|
||
|
|
||
|
import (
|
||
|
"errors"
|
||
|
"expenses/model"
|
||
|
"fmt"
|
||
|
"gorm.io/driver/postgres"
|
||
|
"gorm.io/gorm"
|
||
|
)
|
||
|
|
||
|
func InitDB(conf model.DataSource) (*gorm.DB, error) {
|
||
|
// 拼接下 dsn 参数, dsn 格式可以参考上面的语法
|
||
|
//这里使用 Sprintf 动态拼接 dsn 参数,因为一般数据库连接参数,我们都是保存在配置文件里面,需要从配置文件加载参数,然后拼接 dsn。
|
||
|
dsn := fmt.Sprintf("host=%v user=%v password=%v dbname=%v port=%d sslmode=disable TimeZone=Asia/Shanghai",
|
||
|
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
|
||
|
}
|
||
|
|
||
|
return db, nil
|
||
|
}
|