How to save the memory layer from QGIS in PostGIS database in specific schema (public) using PyQGIS or python?

Here some example from my code :

outputs_QGISDIFFERENCE_1=processing.runalg('qgis:difference', layer1,layer2,False,None)
load=QgsVectorLayer(outputs_QGISDIFFERENCE_1['OUTPUT'], 'myname', 'ogr')

One way is using line :

load=QgsVectorLayer(outputs_QGISDIFFERENCE_1['OUTPUT'], 'myname', 'ogr')

to get the layer from algorithm.

Or another way is :


to get the layer from the path.

But how to save this layer in PostGIS database?

2 Answers 2


Perhaps @firefly-orange can be proven wrong ;-)

I found something on the web that answers your question: http://ssrebelious.blogspot.com/2015/06/how-to-import-layer-into-postgis.html

The guy uses QgsVectorLayerImport.importLayer() method which applies for QGIS 2.x (https://qgis.org/api/2.8/classQgsVectorLayerImport.html)

For QGIS 3.x it has been renamed to QgsVectorLayerExporter, cp. https://qgis.org/api/api_break.html#qgis_api_break_3_0_QgsVectorLayerExporter as well as the documentation under https://qgis.org/api/classQgsVectorLayerExporter.html, the method is now called exportLayer()

Here is some code that worked for me:

#my_layer is some QgsVectorLayer
con_string = """dbname='postgres' host='some IP adress' port='5432' user='postgres' password='thepassword' key=my_id type=MULTIPOLYGON table="myschema"."mytable" (geom)"""
err = QgsVectorLayerExporter.exportLayer(my_layer, con_string, 'postgres', QgsCoordinateReferenceSystem(epsg_no), False)

The layer seems to need a primary key (here: key=my_id) and (geom) is the geometry column.

As pointed out in the blog entry, a list of provider keys can be obtained by

>>> QgsProviderRegistry.instance().providerList()
['DB2', 'WFS', 'arcgisfeatureserver', 'arcgismapserver', 'delimitedtext', 'gdal', 'geonode', 'gpx', 'grass', 'grassraster', 'mdal', 'memory', 'mesh_memory', 'mssql', 'ogr', 'oracle', 'ows', 'postgres', 'spatialite', 'virtual', 'wcs', 'wms']
  • It work for me but I need to save processing result into shapefile before export it on postgis database (QgsProcessing.TEMPORARY_OUTPUT don't work). For use it in a loop, which argument can I add for overwrite layer in my postgis database? Sep 10, 2019 at 13:23
  • This does work for temporary layers, the trick is you need to get the output from the dictionary: temp_layer['OUTPUT']
    – thayer
    Mar 20, 2021 at 4:46

I'm not sure if you can save the output directly in PostGIS, though I'd be happy to be proved wrong. You could save the output as shp then use the shp2pgsql utility as a sub process. This question will provide the code you need to add to your python script.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.