如何使用gorm连接到postgresql?

fruv7luv  于 2022-12-07  发布在  Go
关注(0)|答案(1)|浏览(265)

如何使用gorm连接到postgresql?(致命错误:用户“postgres”的口令验证失败(SQLSTATE 28P01))

package model

import (
    "gorm.io/driver/postgres"
    "gorm.io/gorm"
)

var db *gorm.DB

func init() {
    var err error
    dsn := "host=localhost user=postgres dbname=postgres port=5432 sslmode=disable TimeZone=Asia/Tokyo"
    db, err =  gorm.Open(postgres.Open(dsn), &gorm.Config{})
    if err != nil {
      panic("failed to connect database")
    }
    db.AutoMigrate(&User{})
    db.AutoMigrate(&Todo{})
}
7cwmlq89

7cwmlq891#

您可以尝试以下操作:使用Sprintf声明dsn

host := "localhost"
user := "postgres"
password := ""
dbname := "DBNAME"
port := "5432"

dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%s sslmode=disable",
    host, user, password, dbname, port)
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{
    SkipDefaultTransaction: true,
})
if err != nil {
    panic(err)
}

并检查数据库连接用途:

func TestConnect(t *testing.T) {
//your DB setup function

}

相关问题