Retrieve available PostGIS connections in PyQGIS

To get the information you want, you need to use the QSettings class. This uses a hierarchical structure, like the Windows registry. If you have the latest version of QGIS, you can see this hierarchy using Settings>Options>Advanced

The following code works from the Python Console. I've not tried this from a plugin or outside of QGIS, so some additional work might be required in these cases.

To see the hierarchy, use this in the QGIS python console...

from PyQt4.QtCore import QSettings
qs = QSettings()
for k in sorted(qs.allKeys())
    print k

The output gives some hints...

.. snip ..
Plugins/searchPathsForPlugins
Plugins/valuetool/mouseClick
PostgreSQL/connections/GEODEMO/allowGeometrylessTables
PostgreSQL/connections/GEODEMO/database
PostgreSQL/connections/GEODEMO/dontResolveType
PostgreSQL/connections/GEODEMO/estimatedMetadata    
.. snip ...

So you can get database connection details by filtering for the prefix PostgreSQL/Connections/

So in this case I have a connection called GEODEMO, I can get the username like so...

from PyQt4.QtCore import QSettings
qs = QSettings()
print qs.value("PostgreSQL/connections/GEODEMO/username")
>> steven

Once you have a database in mind, you can retrieve a list of tables using the PostGisDBConnector class.

import db_manager.db_plugins.postgis.connector as con
from qgis.core import QgsDataSourceURI

uri = QgsDataSourceURI()
uri.setConnection("127.0.0.1", "5432", "database_name", "username", "password")
c = con.PostGisDBConnector(uri)
print c
print c.getTables()

Note that the port should be a string, not a number.


My answer will be nearly the same as the previous one but you can avoid to loop all the settings and only obtain PostgreSQL connexions with

from PyQt4.QtCore import QSettings

s = QSettings()
s.beginGroup("PostgreSQL/connections")

print s.allKeys()
print s.value("GEODEMO/username") 

s.endGroup()