英文:
How do I connect to postgresql with gorm?
问题
如何使用gorm连接到postgresql?(FATAL:用户“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{})
}
以上是使用gorm连接到postgresql的示例代码。你需要将dsn
变量中的连接信息修改为你的postgresql数据库的实际信息,包括主机名、用户名、密码、数据库名和端口号等。如果连接成功,代码会自动迁移User
和Todo
两个模型对应的表结构。如果连接失败,代码会抛出一个panic异常。
英文:
How do I connect to postgresql with gorm? (FATAL: password authentication failed for user "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{})
}
答案1
得分: 0
你可以尝试这样做:使用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
}
英文:
you can try this instead : Use Sprintf to declare 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)
}
and check the database connection use :
func TestConnect(t *testing.T) {
//your DB setup function
}
答案2
得分: 0
在我使用Windows作为操作系统的情况下,我需要卸载Postgres。
然后打开Docker Desktop和终端,并创建一个容器:
-
docker run --name some_name -e POSTGRES_USER=your_name -e POSTGRES_PASSWORD=your_password -p 5432:5432 -d postgres
-
docker exec -it some_name bash
-
psql -U your_name --password(按回车键并输入密码)
-
CREATE DATABASE db_name;
-
\c db_name(按回车键并输入密码)
完成。不要关闭终端,使用另一个终端并执行程序。
英文:
In my case using windows as the OS, I had to uninstall postgres.
then open docker desktop and a terminal and create a container with:
-
docker run --name some_name -e POSTGRES_USER= your_name -e POSTGRES_PASSWORD= your_password -p 5432:5432 -d postgres
-
docker exec -it some_name bash
-
psql -U your_name --password (press enter and enter the password)
-
CREATE DATABASE db_name;
-
\c db_name (press enter and enter the password)
Done. Don't close the terminal, use another and execute the program.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论