I am looking for an "elegant" solution to write, from a python script, a layer from qgis and into a new table of a PostGIS database. I thougth that this might be solved by QgsWriteVectorLayer, but I could not find any hint that this is supported. I only found the solution that this can be done e.g. with Qtsql, but then one has to:

  1. analyse the layer (field names, field datatypes, srid, ... )
  2. create the table and
  3. fill the table with date.

Question: Does pygis offers a "simple" solution to write a complete layer directly into a new PostGIS table?

  • I would use ogr2ogr: ogr2ogr -f PostgreSQL PG:dbname=mydb myshape.shp. – Jakob Jul 30 '14 at 8:12
  • this solution does not work because the layer is not a shape file but a memory layer in qgis. Exporting the memory layer to shapefile does not work because e.g. string length for fieldnames is limited in shapefiles. additionally, i do not have access to ogr2ogr in that particular environment. – gallay Jul 30 '14 at 16:47

In order to write to the database QgsVectorLayerImport.importLayer() function have to be used.

uri = "dbname='test' host=localhost port=5432 user='user' password='password' key=gid type=POINT table=\"public\".\"test\" (geom) sql="
crs_id = 4326
crs = QgsCoordinateReferenceSystem(crs_id, QgsCoordinateReferenceSystem.EpsgCrsId)
# layer - QGIS vector layer
error = QgsVectorLayerImport.importLayer(layer, uri, "postgres", crs, False, False)
if error[0] != 0:
    iface.messageBar().pushMessage(u'Error', error[1], QgsMessageBar.CRITICAL, 5)
| improve this answer | |

You can import your shapefile to a postgis database with this python command :

import os
#Import shapefile to postgis DB
os.system("shp2pgsql -s SRID -c -D -I /path/shape.shp tablename | psql -d dbname -h localhost -U username")

(Just change : SRID (ex 4326), tablename (give any name), path, dbname and username).

| improve this answer | |
  • 1
    this solution does not work because the layer is not a shape file but a memory layer in qgi (see my comment above) – gallay Jul 30 '14 at 16:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.