1

I've tried to add my temporary table into QGIS canvas using pyqgis but it's failed. Here the code(view_tatanga is a temporary table that I've created using sql on pgadmin) :

uri = QgsDataSourceURI()
sql = "SELECT * FROM gis.view_tatanga"
uri.setConnection("localhost", "5433", "db_pbb", "postgres", "septin")
uri.setDataSource('', u'(%s\n)' % sql, 'geom', '', 'nop')
#uri.setDataSource("",sql,"geom","","nop")
tmadminkec = QgsVectorLayer(uri.uri(), 'view_tatanga', "postgres")
QgsMapLayerRegistry.instance().addMapLayer(tmadminkec)

I didn't get any error when I try to load a usual table (non temporary table). Any ideas ?

tinlyx
11.3k18 gold badges78 silver badges130 bronze badges
asked Oct 6, 2016 at 7:28
1
  • Try uri.setDataSource('gis', 'view_tatanga', 'geom', '', 'nop') Note that nop must be a field with unique values. Commented Oct 6, 2016 at 12:22

1 Answer 1

2

You don't need the sql parameter! In particular, it only takes the where clause, so the name sql is misleading. See Adding PostGIS layer from QGIS Python plugin for a simple example.

supplement:

if you want the result of an sql query shown as a layer, you'll have to reproduce the behaviour of the qgis database manager. Here the connection replaces the table name with sql string. I did this with a spatialite db.

# the specific connect-string for spatialite
sConnect = "dbname='" + myDBName + "'"
# table contains sql 
table = "select mytable.field1, ..." + "where myTable.field1 >= 100"
# putting together as a uri-String
uri = sConnect + " key='myNumerfield'" + "table=\"(%s)\" (geom) sql=" % table
display_name = 'SQL-Result'
# create vector layer
vlayer = QgsVectorLayer(uri, display_name, 'spatialite')

You want to find out, how the connection string for postgres looks like. Load a layer through the database manager and look into the layer properties. May this helps you!

answered Oct 6, 2016 at 7:48

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.