QGIS 3.x
In QGIS 3.x, you can write a layer to Postgis using QgsVectorLayerExporter.exportLayer()
, as documented.
Postgresql provider uri
The Postgresql provider uri
indicates the destination database server, table, geometry column and primary key field.
It depends on how you connect to the database.
If you provide hostname, database, username and password, the uri
should be like:
uri = 'dbname=\'miebiom\' host=localhost port=5432 user=\'geobox\' password=\'geobox\' sslmode=disable table="public"."import" (geom) key=\'id\''
If you use libpq services to connect, just use:
uri = 'service=covid table="public"."import" (geom) key=\'id\''
Usage example
In the following example, an existent layer called distrito
is written to a table public.import
.
project = QgsProject.instance()
lyr = project.mapLayersByName('distrito')[0]
uri = 'dbname=\'miebiom\' host=localhost port=5432 user=\'geobox\' password=\'geobox\' sslmode=disable table="public"."import" (geom) key=\'id\' '
err = QgsVectorLayerExporter.exportLayer(lyr, uri, "postgres", lyr.crs() )
if err[0] != QgsVectorLayerExporter.NoError:
print('Import layer {} failed with error {}'.format( lyr.name(), err) )
else:
print('Layer {} import ok'.format( lyr.name() ) )
Options
You can add additional options to QgsVectorLayerExporter.exportLayer()
.
Common options to all providers:
overwrite
(False, if not provided)
forceSinglePartGeometryType
(False, if not provided)
Postgresql provider specific option:
lowercaseFieldNames
(False, if not provided)
Usage example with all options:
err = QgsVectorLayerExporter.exportLayer(lyr, uri, "postgres", lyr.crs(),
options = { "overwrite": True, "forceSinglePartGeometryType": True, "lowercaseFieldNames": True } )
Non geographic layers
For non geographic layers, just remove the geometry column from the uri
. You can check if the layer is geographic or not with lyr.geometryType()
.
Other examples on QGIS unit tests
A good source of usage examples are QGIS unit tests. Follow this link, for usage examples written by QGIS developers.
QgsVectorFileWriter.writeAsVectorFormat()
?