Tuesday 22 August 2017

Empty layer after import into PostGIS Database. Pyqgis


I'm facing troubles to import a layer into a PostGIS database with pyqgis in a script. Here is my code:


Nombre_BBDD='test'
host='localhost'
puerto='5432'
usuario='postgres'
password='xxxxxxx'
Nombre_Tabla='table'
Llave_primaria='id'

Capa_a_procesar='/xxxxxxx/shapefile.SHP'
Tipo_geometria='POLYGON'

capaImportar = QgsVectorLayer(Capa_a_procesar, 'capaImportar', 'ogr')
uri = """dbname='"""+Nombre_BBDD+"""' host='"""+host+"""' port="""+puerto+""" user='"""+usuario+"""' password='"""+password+"""' key="""+Llave_primaria+""" type="""+Tipo_geometria+""" table=\"public\".\""""+Nombre_Tabla+"""\" (geom) sql="""
crs = QgsCoordinateReferenceSystem(25830)
error = QgsVectorLayerImport.importLayer(capaImportar, uri, "postgres", crs, False, True)

I was trying to do it how is recommended in this link.


It seems everything is right, but when I try to load the layer this is empty and the python console throws this error:




Exception RuntimeError: 'wrapped C/C++ object of type PGVectorTable has been deleted' in bound method PGTableDataModel.del of db_manager.db_plugins.postgis.data_model.PGTableDataModel object at 0x7f3f24190d60 ignored



I'm working with qgis 2.18.10 in a Kubuntu 16.04



Answer



This method worked well to import layers to PostGIS:


dbname= 'dbname'
host= 'localhost'
user= 'postgres'
password= 'password'

port= '5432'
vlayerPath='path/to/shapeFile/file.shp'


import os
command = "ogr2ogr -lco GEOMETRY_NAME=geom -a_srs epsg:25830 -f 'PostgreSQL' PG:'dbname=" + dbname + \
" host=" + host + \
" user=" + user + \
" password=" + password + \
" port=" + port + "'" + \

" '"+ vlayerPath+"'"

os.system(command)

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...