Reputation: 261
Could someone please explain how to obtain a list of all existing databases on a PostgreSQL server, to which the user already has access, using Qt? PostgreSQL documentation suggests the following query:
SELECT datname FROM pg_database WHERE datistemplate = false;
What are the correct parameters to the following functions:
QSqlDatabase::setDatabaseName(const QString & name) //"postgres" or "pg_database"?
QSqlDatabase::setUserName(const QString & name) //actual user name?
QSqlDatabase::setPassword(const QString & password) //no password? or user password?
Much appreciated. Thank you in advance.
Upvotes: 3
Views: 1925
Reputation: 324395
You appear to have already answered the first part of your question. Connect to the postgres or template1 database and issue the query you've quoted above to get a list of databases. I'm guessing - reading between the lines - that you don't know how to connect to PostgreSQL to send that query, and that's what the second part of your question is about. Right?
If so, the QSqlDatabase
accessor functions you've mentioned are used to set connection parameters, so the "correct" values depend on your environment.
If you want to issue the query above - to list databases - then you would probably want to connect to the postgres
database as it always exists and isn't generally used for anything specific, it's there just to be connected to. That means you'd call setDatabaseName("postgres");
. Passing pg_database
to setDatabaseName
would be nonsensical, since pg_database
is the pg_catalog.pg_database
table, it isn't a database you can connect to. pg_database
is one of those odd tables that exists in every database, which might be what confused you.
With the other two accessors specify the appropriate username and password for your environment, same as you'd use for psql
; there's no possible way I could tell you which ones to use.
Note that if you set a password but one isn't required because authentication is done over unix socket ident, trust, or other non-password scheme the password will be ignored.
If this doesn't cover your question, consider editing it and explaining your problem in more detail. What've you tried? What didn't work how you expected? Error messages? Qt version?
Upvotes: 2