Postgresql tries to connect to a Db with the same name as the user, even when I specify the DB name in the connection string.
Cadena de conexión:
host=localhost port=5432
user=carsUser
password= dbname=the-new-cars
sslmode=disable 2024/06/22 16:00
Error al hacer ping a la base de datos: pq: database "carsUser" does not exist
It tries to connect to database carsUser, but that’s the name of the user.. I know PostgreSQL can try to connect by default to a DB with the same name, but …how can I hard/force specify the DB name?
func main() {
// Cargar variables de entorno desde el archivo .env
err := godotenv.Load()
if err != nil {
log.Fatal("Error al cargar el archivo .env: ", err)
}
fmt.Println("Archivo .env cargado correctamente")
// Configurar la cadena de conexión
connStr := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=require",
os.Getenv("DB_HOST"),
os.Getenv("DB_PORT"),
os.Getenv("DB_USER"),
os.Getenv("DB_PASSWORD"),
os.Getenv("DB_NAME"))
fmt.Println("Cadena de conexión:", connStr)
// Conectar a la base de datos
db, err := sql.Open("postgres", connStr)
if err != nil {
log.Fatal("Error al abrir la conexión a la base de datos: ", err)
}
defer db.Close()
I try with that code, works only if the db has the same name as the user
2
Answers
Try putting semi-colons between the items in the connection string:
Reference https://www.connectionstrings.com/progress/
As per the docs
You probably believe that this does not apply here, because you are specifying
dbname
, but there is an issue:password= dbname=the-new-c
lib/pq
/jackc/pgx
will parse this as "set the password toname=the-new-c
". To fix this follow the docs:i.e.
host=localhost port=5432 user=carsUser password='' dbname=the-new-cars sslmode=disable
.