简体   繁体   English

使用 PyQGIS 3.10 和更高版本获取 PostGIS 表列表

[英]Get PostGIS table list with PyQGIS 3.10 and newer

I have to load some PostGIS layers with PyQGIS to QGIS projects.我必须将一些带有 PyQGIS 的 PostGIS 图层加载到 QGIS 项目中。 Until Version 3.8 of QGIS I had a working solution.在 QGIS 3.8 版之前,我有一个可行的解决方案。 The Connection is made with this code:使用以下代码进行连接:

from qgis.core import QgsDataSourceUri, QgsVectorLayer, QgsDataSourceUri
import re
import time
import db_manager.db_plugins.postgis.connector as con

...

class PgConnection:
    def __init__(self, host, dbname, port):
        self.uri = QgsDataSourceUri()
        self.host = host
        self.dbname = dbname
        self.port = port
        self.authcfg = None
        self.user = ''
        self.passwd = ''
        settings = QgsSettings()
        settings.beginGroup('PostgreSQL/connections')
        for connectionName in settings.childGroups():
            if settings.value(f'{connectionName}/host') == host and \
                settings.value(f'{connectionName}/database') == dbname:
                    self.authcfg = settings.value(f'{connectionName}/authcfg')
                    break
        if self.authcfg is None:
            self.uri.setConnection(self.host, port, self.dbname, None, None)
            connInfo = self.uri.connectionInfo()
            (success, user, passwd) = QgsCredentials.instance().get(connInfo, None, None)
            if success:
                self.uri.setPassword(passwd)
                self.uri.setUsername(user)
        else:
            self.uri.setConnection(self.host, self.port, self.dbname, None, None, authConfigId=self.authcfg)

Now I need to get all tables from a specific schema.现在我需要从特定模式中获取所有表。 Until QGIS version 3.8 I used following code for this (in the same class):在 QGIS 3.8 版之前,我为此使用了以下代码(在同一类中):

def getPgTableNames(self, schema):
    tablenames = con.PostGisDBConnector(self.uri)
    return tablenames.getTables(schema)

Since version 3.10 this is not longer working as con.PostGisDBConnector(self.uri) throws an error.从 3.10 版开始,这不再有效,因为 con.PostGisDBConnector(self.uri) 会引发错误。 What is the correct way to get the tablenames?获取表名的正确方法是什么?

It took a while to find my error.花了一段时间才发现我的错误。 The above code does not establish a connection to the database.上面的代码没有建立到数据库的连接。 I did this later when adding layers to the project.我后来在向项目中添加图层时这样做了。 However i had to add following line:但是我必须添加以下行:

self.conn = QgsProviderRegistry.instance().providerMetadata('postgres').createConnection(self.uri.uri(),{})

the function to return the tablelist is now:返回表格列表的 function 现在是:

def getPgTableNames(self):
        tablenames = self.conn.tables(self.schema)
        return tablenames

And the complete code:以及完整的代码:

    from qgis.core import QgsDataSourceUri, QgsVectorLayer, QgsProviderRegistry, QgsProviderMetadata
    import re
    import time
    
    #Klassendefinitionen
    class PgConnection:
        def __init__(self, host, dbname, port, schema):
            self.uri = QgsDataSourceUri()
            self.host = host
            self.dbname = dbname
            self.port = port
            self.schema = schema
            self.authcfg = None
            self.user = ''
            self.passwd = ''
            pgProvider = QgsProviderRegistry.instance().providerMetadata('postgres')
            settings = QgsSettings()
            settings.beginGroup('PostgreSQL/connections')
            for connectionName in settings.childGroups():
                if settings.value(f'{connectionName}/host') == host and \
                    settings.value(f'{connectionName}/database') == dbname:
                        self.authcfg = settings.value(f'{connectionName}/authcfg')
                        break
            if self.authcfg is None:
                self.uri.setConnection(self.host, port, self.dbname, None, None)
                connInfo = self.uri.connectionInfo()
                (success, user, passwd) = QgsCredentials.instance().get(connInfo, None, None)
                if success:
                    self.uri.setPassword(passwd)
                    self.uri.setUsername(user)
            else:
                self.uri.setConnection(self.host, self.port, self.dbname, None, None, authConfigId=self.authcfg)
            
            self.conn = QgsProviderRegistry.instance().providerMetadata('postgres').createConnection(self.uri.uri(),{})
    
        def getPgTableNames(self):
            tablenames = self.conn.tables(self.schema)
            return tablenames
            
    #Verbindungsdaten angeben       
    host = 'some_host'
    dbname = 'some_db'
    schema = 'some_schema'
    port = '1234'
    
    # Verbindung zu Postgis aufbauen
    uri = PgConnection(host,dbname, port, schema)
    tableList = uri.getPgTableNames()
for t in tableList:
    print (t.defaultName())

I just use the connection name and it works.我只是使用连接名称,它可以工作。 I have a connection named ftth and using such name, I can get the connection out of it.我有一个名为ftth的连接,使用这样的名称,我可以从中获取连接

conn = QgsProviderRegistry.instance().providerMetadata('postgres').createConnection('ftth')
conn.tables()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM