I'm looking for write a PyQGIS code to import all layers open in QGIS to PostGIS.

import os
#Code from  https://gis.stackexchange.com/questions/26257/iterating-over-map-layers-in-qgis-python
layers = QgsProject.instance().mapLayers().values()

for layer in layers:
  #Code from https://gis.stackexchange.com/questions/254182/saving-qgis-layer-to-postgis-using-pyqgis
  con_string = """dbname='Robanostra' host='localhost' port='5432' user='Daniele' password='******' key=gid type=MULTIPOLYGON table="s_500_patprova."mytable (geom)"""
  err = QgsVectorLayerExporter.exportLayer(path, con_string, 'postgres', QgsCoordinateReferenceSystem(3003), False)

The result is:

TypeError: QgsVectorLayerExporter.exportLayer(): argument 1 has unexpected type 'str'

I tried to convert str to path but I doesn't work. What am I doing wrong?

1 Answer 1


It seems the first argument of QgsVectorLayerExporter.exportLayer() does not require a string, but the actual QgsMapLayer. Replacing path with the actual layer should work:

import os
layers = QgsProject.instance().mapLayers().values()

for layer in layers:
    con_string = "dbname='RobaNostra' host='localhost' port='5432' user='Daniele' password='Daniele' key=id_urband type=MULTIPOLYGON table='s_500_patprova'." + mytable + " (geom)"
    err = QgsVectorLayerExporter.exportLayer(layer, con_string, 'postgres', QgsCoordinateReferenceSystem(3003), False)
  • Perfect!. Thank you, @Sam Commented Mar 12, 2020 at 9:56

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.