Creating a PostgreSQL Connection From a QGIS Layer Datasource
Sometimes you may want to send SQL to your PostgreSQL database from
a plugin or PyQGIS script. To do this, you need a connection to your
database. Since QGIS uses its own low-level interface to PostgreSQL, it
can’t provide a connection for general query use. You can, however, use the
information from the QGIS PostgreSQL data provider to create your own connection using
QSqlDatabase, a Qt class.
You could use QSettings to read the stored connection information from
your settings, but
this may not always work if the password isn’t stored with the connection.
Here is an example that uses the active layer in QGIS to get the connection
parameters, create a connection, and execute a query that returns some
data:
"""Use the database provider to connect to PostgreSQL.This script is set up to run under the Script Runner plugin, butcan be also be run from the Python console."""fromPyQt4.QtCoreimport*fromPyQt4.QtGuiimport*fromPyQt4.QtSqlimport*fromqgis.coreimport*defrun_script(iface):# get the active layerlayer=iface.activeLayer()# get the underlying data providerprovider=layer.dataProvider()ifprovider.name()=='postgres':# get the URI containing the connection parametersuri=QgsDataSourceURI(provider.dataSourceUri())printuri.uri()# create a PostgreSQL connection using QSqlDatabasedb=QSqlDatabase.addDatabase('QPSQL')# check to see if it is validifdb.isValid():print"QPSQL db is valid"# set the parameters needed for the connectiondb.setHostName(uri.host())db.setDatabaseName(uri.database())db.setPort(int(uri.port()))db.setUserName(uri.username())db.setPassword(uri.password())# open (create) the connectionifdb.open():print"Opened %s"%uri.uri()# execute a simple query query=db.exec_("""select * from qgis_sample.airports order by name""")# loop through the result set and print the namewhilequery.next():record=query.record()printrecord.field('name').value().toString()else:err=db.lastError()printerr.driverText()
Another approach is to use the psycopg2 Python module to create
a connection using the data source URI of the active layer.