5

I need to insert the data of a layer of the qgis project into an existing table of postgis I have been using this code to test, but it gives an error since the method used creates the table in postgresql does not insert the elements if the layer exists.

def test_insertar_en_Postgis(self):
    app = QgsApplication.instance()
    self.conf = QgsSettings(
        app.qgisSettingsDirPath() + "QGIS/gestion_proyectos.ini", QSettings.IniFormat
    )

    self.conf.beginGroup("/conexion")
    self.servidor = self.conf.value("servidor")
    self.puerto = self.conf.value("puerto")
    self.conf.endGroup()
    self.conf.beginGroup("/cfg_nomenclatura")
    self.nomenclatura = self.conf.value("nomenclatura")
    self.directorio = self.conf.value("directoriogpk")

    self.usuario = self.cfgdlg.v_usuario.text()
    self.contrasena = self.cfgdlg.v_contrasena.text()

    layers = self.iface.mapCanvas().layers()
    indice =0;
    for layer in layers:
        indice= indice + 1
        con_string = "dbname='bdsapromat' host='" + self.servidor + "' port='" + self.puerto + "' user='" + self.usuario + "' password='" + self.contrasena + "' key=geo_id type= GEOMETRY  table= \"25_areas_verdes_terrenos\".test"+str(indice)+" (geom)"

        err = QgsVectorLayerExporter.exportLayer(layer, con_string, 'postgres',QgsCoordinateReferenceSystem('4326'),True)

        if err != 0:
            QgsMessageLog.logMessage('Hay error al insertar en postgis ', "Proyecto", level=Qgis.Info)
0

1 Answer 1

4

I have solved the problem I had to add elements to an existing postgis table from qgis using pyqgis, for this I have used the plugin developed by Germán Carrillo Append features to layer, calling it from pyqgis as a Processing algorithm. I enter the new code

def insertar_en_Postgis(self):
    app = QgsApplication.instance()
    self.conf = QgsSettings(
        app.qgisSettingsDirPath() + "QGIS/gestion_proyectos.ini", QSettings.IniFormat
    )

    self.conf.beginGroup("/conexion")
    self.servidor = self.conf.value("servidor")
    self.puerto = self.conf.value("puerto")
    self.conf.endGroup()
    self.conf.beginGroup("/cfg_nomenclatura")
    self.nomenclatura = self.conf.value("nomenclatura")
    self.directorio = self.conf.value("directoriogpk")

    self.usuario = self.cfgdlg.v_usuario.text()
    self.contrasena = self.cfgdlg.v_contrasena.text()
    uritarget = QgsDataSourceUri()
    uritarget.setConnection(self.servidor, str(self.puerto), "bdsapromat", self.usuario, self.contrasena,
                            QgsDataSourceUri.SslDisable)
    uritarget.setSrid('4326')

    alllayers = QgsProject.instance().mapLayers().values()

    for layerorigen in alllayers:
        uritarget.setDataSource('public', layerorigen.name(), "geom", '')
        self.target = QgsVectorLayer(uritarget.uri(), layerorigen.name(), "postgres")
        processing.run("etl_load:appendfeaturestolayer", {
        'SOURCE_LAYER': layerorigen,
        'SOURCE_FIELD': 'geo_id',
        'TARGET_LAYER': self.target,
        'TARGET_FIELD': 'geo_id',
        'ACTION_ON_DUPLICATE': 2})

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.