首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何加载Postgres QgsVectorLayer

如何加载Postgres QgsVectorLayer
EN

Stack Overflow用户
提问于 2021-02-06 03:05:25
回答 1查看 162关注 0票数 0

我有一个QGIS脚本,我正在尝试加载存储在Postgres数据库中的矢量层。当我打印层的isValid()方法时,我得到False。下面是我的代码:

代码语言:javascript
复制
from qgis.core import *

db_client = 'postgres'
db_host = 'localhost'
db_port = '5432'
db_name = 'database'
db_user = 'user'
db_password = 'pass123'
db_schema = 'public'
tablename = 'Geo_Layer'
geometrycol = 'geom'
tract_number_index = 3

QgsApplication.setPrefixPath('/usr/bin/qgis', True)
qgs = QgsApplication([], False)
qgs.initQgis()

geo_uri = QgsDataSourceUri()
geo_uri.setConnection(db_host, db_port, db_name, db_user, db_password)
geo_uri.setDataSource(db_schema, tablename, geometrycol, '', 'id')
geo_layer = QgsVectorLayer(geo_uri.uri(False), "Test", "postgres")
# Other configurations I have tried
# geo_layer = QgsVectorLayer(geo_uri.uri(), "Test", "postgres")
# geo_layer = QgsVectorLayer(geo_uri.uri(), "Test", "ogr")
# geo_layer = QgsVectorLayer(geo_uri.uri(False), "Test", "ogr")
print(geo_layer.isValid())

qgs.exitQgis()

我已经提供了我尝试过的其他QgsVectorLayer配置。所有打印该层无效。

QGIS版本: 3.16.3-Hannover Python版本: 3.8.5 Ubuntu版本: 20.04.02 LTS

我已经用DBeaver检查了我的凭据,我可以连接了。

EN

回答 1

Stack Overflow用户

发布于 2021-02-08 00:00:57

当我在postgis中的几何列包含多个几何类型时,我曾经遇到过这个问题。在这种情况下,您可以首先过滤几何图形类型的列,然后为每个几何图形类型构造一个用于qgis的图层:

代码语言:javascript
复制
for geom in geometry_types:
    uri.setDataSource(schema, table, column, "GeometryType(%s)= '%s'" % (column, geom))
    vlayer = QgsVectorLayer(uri.uri(), layer_name, "postgres")
    print(vlayer.isValid())

可以使用以下查询检查postgis中的几何图形类型:

代码语言:javascript
复制
SELECT DISTINCT(GeometryType("%s"::geometry)) FROM "%s";""" % (column, table)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66069177

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档