2

What if I would like to have the full SpatiaLite database path from a vector layer loaded in the TOC with PyQGIS?

With a very simple example, by storing active vector layer in a variable:

vl = iface.activeLayer()

one can retrieve the providerType and the dataSourceUri:

vl.providerType()
u'spatialite'

vl.dataProvider().dataSourceUri()
vl.dataProvider().dataSourceUri()
u'dbname=\'/home/matteo/myDataBase.sqlite\' table="river_layer" (geometry) sql='

Is there a simple method to get as a string, just the path of the database (so. /home/matteo/myDataBase.sqlite)?

  • 1
    Thanks Joseph! Do you think (or know) if the method you suggest is also cross-platform? Great pythonic way to solve the problem ;) – matteo Jun 14 '17 at 13:53
  • Most welcome! Hmm I can't tell you for sure, I tested this on a Windows machine so if it works for you too then that's two platforms down ;) – Joseph Jun 14 '17 at 13:56
  • 1
    ehehe.. 2 down is good.. Thanks Joseph, if want you can copy and paste your comment as a question so I will accept it. Thanks again! – matteo Jun 14 '17 at 14:08
3

Similar to this question but if you only want to extract the path of the dataSourceUri() (and not u'dbname=\'/home/matteo/myDataBase.sqlite\'), you could use:

vl.dataProvider().dataSourceUri().split(' ')[0].replace('dbname=','').replace("'","")

Which should give:

u'/home/matteo/myDataBase.sqlite'
  • 1
    Question about that: Why don't you use vl.source() instead of vl.dataProvider().dataSourceUri()? – YoLecomte Jun 14 '17 at 14:56
  • @YoLecomte - You're correct in that you could use vl.source() to extract the uri path which could shorten it to vl.source().split(' ')[0].replace('dbname=','').replace("'",""). But typically when using Spatialite (or PostGIS) databases, you use vl.dataProvider().dataSourceUri() to not only extract the uri information but also set up the connection parameters. I guess in the end, it's just personal preference :) – Joseph Jun 14 '17 at 15:05
  • @YoLecomte - Most welcome =) – Joseph Jun 14 '17 at 15:10

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.