3

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)?

mgri
16.4k6 gold badges48 silver badges80 bronze badges
asked Jun 14, 2017 at 13:26
3
  • 1
    Thanks Joseph! Do you think (or know) if the method you suggest is also cross-platform? Great pythonic way to solve the problem ;) Commented Jun 14, 2017 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 ;) Commented Jun 14, 2017 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! Commented Jun 14, 2017 at 14:08

1 Answer 1

4

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'
answered Jun 14, 2017 at 14:17
3
  • 1
    Question about that: Why don't you use vl.source() instead of vl.dataProvider().dataSourceUri()? Commented Jun 14, 2017 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 :) Commented Jun 14, 2017 at 15:05
  • @YoLecomte - Most welcome =) Commented Jun 14, 2017 at 15:10

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.