I'm writing a custom Processing script that needs to know which database connection a vector layer resides in. I can't find anywhere in the API a function to return this information from a layer. So I guess I have two questions:

  1. Is there a Python function (either from qgis.core or from Processing tools) that easily returns things like the DB name, schema, etc. of a given layer?
  2. If not, do I need to parse the URI of the layer? How do I get that information?

2 Answers 2


I ended up writing a small module to extract information out of the string that source() returns:

import re

class LayerDbInfo:
    def __init__(self, layerInfo):
        if layerInfo[:6] == 'dbname':
            layerInfo = layerInfo.replace('\'','"')
            vals = dict(re.findall('(\S+)="?(.*?)"? ',layerInfo))
            self.dbName = str(vals['dbname'])
            self.key = str(vals['key'])
            self.user = str(vals['user'])
            self.password = str(vals['password'])
            self.srid = int(vals['srid'])
            self.type = str(vals['type'])
            self.host = str(vals['host'])
            self.port = int(vals['port'])

            # need some extra processing to get table name and schema
            table = vals['table'].split('.')
            self.schemaName = table[0].strip('"')
            self.tableName = table[1].strip('"')

    def getDBName(self):
        return self.dbName

    def getHost(self):
        return self.host

    def getPort(self):
        return self.port

    def getKey(self):
        return self.key

    def getUser(self):
        return self.user

    def getPassword(self):
        return self.password

    def getSRID(self):
        return self.srid

    def getType(self):
        return self.type

    def getSchema(self):
        return self.schemaName

    def getTable(self):
        return self.tableName

I think you could use the following code to obtain source information for your layer. Select a layer from the layer window and input the code into the Python Console:

layer = qgis.utils.iface.activeLayer()
print layer.source()

You should receive information about the layer.

Hope this helps!

  • Thanks. This gets me what I need, although it would be nice if there were an easy way to pull out pertinent pieces of the connection string. Something like layer.dbname(). Jul 31, 2015 at 1:11
  • @spencerrecneps - Most welcome buddy! I just found another post where the answer explains how you could print specific information from the source. You could adapt this to pull out whatever information you need.
    – Joseph
    Jul 31, 2015 at 9:41

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.