Why do I incorrectly get connected to another database when using Postgresql and PQconnectdb?

72 Views Asked by At

I installed postgresql by postgres database. Postgresql version 12.17. Then, I created new database: myendb.

I'm using libpq.

I tried to connect myendb by following connection string and using PQconnectdb() function:

host=localhost port=54312 user=postgres password= dbname=myendb

User has empty password.

Then I performed the following command:

SELECT current_database();

And libpq gave to me following result:

postgres

This is wrong, because I've connected to myendb database.

Do you know why? But I've connected to myendb database.

After I used PQsetdbLogin() instead of PQconnectdb(), libpq connects to myendb that I expected.

Why PQsetdbLogin and PQconnectdb have some differences?

The documentation says:

It has the same functionality except that the missing parameters will always take on default values.

https://www.postgresql.org/docs/8.1/libpq.html

1

There are 1 best solutions below

0
On

You have set your password to 'dbname=myendb', and have not set your dbname to anything so it defaults to 'postgres'. If you don't want to set your password, just don't mention it in the connection string. (or, do as the docs you link to say: "To write an empty value...surround it with single quotes")

You can't simply use PQsetdbLogin() instead of PQconnectdb() as they have different signatures. You must have parsed out the string to get the individual parameters, which you did differently than the way PostgreSQL does it.