首页 > 解决方案 > 由没有密码的用户连接到 Postgres DB

问题描述

我通过以下方式创建了一个用户:

sudo -u postgres psql -c "CREATE USER sample;"

然后创建了一个数据库:

sudo -u postgres psql -c "CREATE DATABASE practice OWNER sample;"

现在我正在尝试通过以下代码段连接到该数据库:

dsn := url.URL{
        User:     url.UserPassword("sample", ""),
        Scheme:   "postgres",
        Host:     fmt.Sprintf("%s", "localhost"),
        Path:     "practice",
        RawQuery: (&url.Values{"sslmode": []string{"disable"}}).Encode(),
}
db, err := gorm.Open(
        "postgres",
        dsn.String(),
)
if err != nil {
        log.Fatal(err)
}

但输出是:

2020/07/07 16:43:44 pq: password authentication failed for user "sample"

如何使用没有密码的用户连接到数据库?

标签: postgresqlgogo-gorm

解决方案


为用户分配密码然后使用它,或者更改您的 pg_hba.conf 文件,以便对该用户/dbname/connection-method/host 使用其他一些身份验证方法(然后重新启动服务器以使更改生效) .

sudo -u postgres psql -c "ALTER USER sample password 'yahkeixuom5R';"

推荐阅读