5

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?

Taras
  • 32,823
  • 4
  • 66
  • 137
Daniele Piccolo
  • 909
  • 4
  • 9

1 Answers1

6

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)
MrXsquared
  • 34,292
  • 21
  • 67
  • 117
Sam
  • 346
  • 1
  • 4