3

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:
  mytable=layer.name()
  path=layer.source()
  #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?

4

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:
    mytable=layer.name()
    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)
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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