TransWikia.com

How to export a table in a geopackage

Geographic Information Systems Asked on September 28, 2020

I’m trying to export a simple PostGIS table loaded in QGIS to a geopackage file.

Here’s an example:

options = QgsVectorFileWriter.SaveVectorOptions()
options.driverName = "GPKG"
options.layerName = "_".join(myLayer.name().split(' '))

geo_package = 'my_gpkg.gpkg'

if not os.path.exists(geo_package):
    options.actionOnExistingFile = QgsVectorFileWriter.CreateOrOverwriteFile
else:
    options.actionOnExistingFile = QgsVectorFileWriter.CreateOrOverwriteLayer

res, text = QgsVectorFileWriter.writeAsVectorFormatV2(myLayer, geo_package, QgsCoordinateTransformContext(), options)

if res == QgsVectorFileWriter.NoError:
     print("Successfull export of layer {}".format(myLayer))
else:
    print("Fail error {}:{}".format(res, text))

It works fine for Vector layers but for a simple PostGIS table, I get the Error code 8 with no Error message.

One Answer

The simple PostGIS table is a table without geometry. Importing it as is was an error and the layer was not valid. I wrongly set the datasource in the uri:

uri = QgsDataSourceUri()
uri.setConnection("MyServerAdress", "5432", "myBase", "user", "pass")
uri.setDataSource(schema, table, "geom")
layer = QgsVectorLayer(uri.uri(False), table, "postgres")
QgsProject.instance().addMapLayer(couche)

Altough I should have done this:

uri = QgsDataSourceUri()
uri.setConnection("MyServerAdress", "5432", "myBase", "user", "pass")
uri.setDataSource(schema, table, None)
layer = QgsVectorLayer(uri.uri(False), table, "postgres")
QgsProject.instance().addMapLayer(couche)

I wrote a topic here:Import a table with no geometry

Correct answer by aurel_nc on September 28, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP