Writing a plugin for QGIS using Python to access PostGIS and write geometries

There are a lot of python plugins for QGIS that access PostGIS. Just download them and check the source code. Accessing PostGIS from Python is quite straight forward (same is true for SpatiaLite by the way).

PostGIS related plugins by name:

  • PgQuery for QGIS
  • PostGIS Manager
  • PostGIS SQL Query Editor
  • RT Sql Layer
  • ...

I have no experience or knowledge of the QGIS API. What I know is that it is a viable approach and it can be a very rewarding experience.

You can check out PyQGIS Cook Book - that shows a lot of code on how to achieve common taks. That might help you.

http://www.mapserver.sk/~wonder/qgis/html/


from pyQGis cookbook:

uri = QgsDataSourceURI()

#set host name, port , database name, username and password
uri.setConnection("localhost ","5432 " , " dbname"," johny","xxx ")

#set database schema, table name, geometry column and optionaly subset(WHERE clause)
uri.setDataSource ("public ","roads ", "the _geom ", "cityid=2643 ")

vlayer=QgsVectorLayer (uri .uri() ,"layer _ name_you_ like","postgres ")