skip to Main Content

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


  1. Try putting semi-colons between the items in the connection string:

    HostName=localhost;PortNumber=5432;LogonID=carsUser; Password=[your_password]; Database=the-new-cars;
    sslmode=disable;

    Reference https://www.connectionstrings.com/progress/

    Login or Signup to reply.
  2. As per the docs

    dbname Defaults to be the same as the user name.

    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/pgxwill parse this as "set the password to name=the-new-c". To fix this follow the docs:

    To write an empty value, or a value containing spaces, surround it with single quotes, for example keyword = ‘a value’

    i.e. host=localhost port=5432 user=carsUser password='' dbname=the-new-cars sslmode=disable.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search