7

How can I add a PostGIS layer to QGIS via the Python Console?

With some server setups, especially with a large number of tables, it can be very slow to load the list of layers via the Browser or Data Source Manager.

asked Oct 25, 2018 at 16:37

1 Answer 1

9

Here are code snippets to add a layer.

I put table name in a variable since it's used twice and the geometry column because that's what I most often change.

QGIS 3.x

tablename = "thetable"
geometrycol = "geom"
from qgis.core import QgsVectorLayer, QgsDataSourceUri
uri = QgsDataSourceUri()
uri.setConnection("host", "5432", "db", "user", "pass")
uri.setDataSource ("schema", tablename, geometrycol)
vlayer=QgsVectorLayer (uri .uri(False), tablename, "postgres")
QgsProject.instance().addMapLayer(vlayer)

QGIS 2.x

tablename = "thetable"
geometrycol = "geom"
from qgis.core import QgsVectorLayer, QgsDataSourceURI
uri = QgsDataSourceURI()
uri.setConnection("host", "5432", "db", "user", "pass")
uri.setDataSource ("schema", tablename, geometrycol)
vlayer=QgsVectorLayer (uri .uri(False), tablename, "postgres")
QgsMapLayerRegistry.instance().addMapLayer(vlayer)
answered Oct 25, 2018 at 16:37

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.