1

I need to import a data table from a database into QGIS using PyQGIS. This table is not QgsVectorLayer and there is not any geometry. That is probably why this is not working. How can I do it?

uri = QgsDataSourceURI()
uri.setConnection("IP_addr", "5432", "gis", "user", "pass")
uri.setDataSource("public", "typy_vykopu", "", "")
table = QgsVectorLayer(uri.uri(), "typy_vykopu_stazene", "postgres")
if not table.isValid():
    print "Table %s did not load" % table.name()
QgsMapLayerRegistry.instance().addMapLayers([table])
  • What does table.isValid() return? – Oscar Campo Apr 25 '18 at 17:25
  • 1
    Thank you for reaction. I just solve my problem. Now I am using psycopg2 for connect to database. – Miroslav Starý Apr 25 '18 at 17:43
  • well, I posted the solution as anyway ;) – Oscar Campo Apr 25 '18 at 17:50
  • it would be "nice" to indicate whether oscar's answer was THE answer to your question ... you apparently want to import a postgis table ... but what does your "This table is not QgsVectorLayer" mean ?... are you talking about your table variable ? meaning there is something wrong with your connection to the database ... ? – snaileater Apr 25 '18 at 19:34
  • @snaileater I guess he was importing data in QGIS a simple Postgresql table without geometry. This could be done with pyqgis using the answer below.... Table variable obviusly is a QgsVectorLayer object.... – Oscar Campo Apr 26 '18 at 9:37
1

You have to set None instead '' for geometry column:

uri = QgsDataSourceURI()
uri.setConnection("IP_addr", "5432", "gis", "user", "pass")
uri.setDataSource("public", "typy_vykopu", None, "")
table = QgsVectorLayer(uri.uri(), "typy_vykopu_stazene", "postgres")
if not table.isValid():
    print "Table %s did not load" % table.name()
QgsMapLayerRegistry.instance().addMapLayers([table])
  • 1
    Ou... this is classic. My problem would be solved by one word. Thank you very much Oscar! – Miroslav Starý Apr 25 '18 at 21:01
  • As snaileater pointed take care that table variable obviusly is a QgsVectorLayer object, but without geometry. – Oscar Campo Apr 26 '18 at 9:40

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.