Python导入Shapefile到PostGIS的常见问题和解决方案

导入Shapefile到PostGIS的常见问题和解决方案

先决条件:

已经拥有含有GDAL的python环境(如果大家需要,我可以后面出一片文章

问题一:QGIS连接到PostGIS数据库失败

错误描述:

Connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused (0x0000274D/10061)

解决方法:

  1. 确认PostgreSQL服务器正在运行。

" Win + R "启动命令行,输入'services.msc',看到如下界面,并找到你所安装的'postgresql'的版本

检查,右边状态列中的状态是否为"正在运行",如果不是,右击该栏-启动

由于我已经启动过,所以就不再做过多演示

问题二:访问被拒绝,无法启动PostgreSQL服务(解决办法同问题一)

错误描述:

在命令行中输入 net start postgresql-x64-16 启动PostgreSQL服务时,报错

发生系统错误 5。拒绝访问。

解决方法:

  1. 以管理员身份运行命令提示符。

  2. 通过Windows服务管理器启动PostgreSQL服务。

  3. 确保PostgreSQL服务的权限设置正确。(如果未解决)

问题三:Unicode解码错误

错误描述:

UnicodeDecodeError: 'gbk' codec can't decode byte

解决方法:

  1. 设置subprocess.run的编码为UTF-8,使用capture_output=True并设置encoding='utf-8'。

  2. 手动解码标准输出和标准错误。

问题四:几何类型不匹配

错误描述:

Geometry type (MultiPolygon) does not match column type (Polygon)

解决方法:

  1. 确保在PostGIS数据库中创建的表可以接受MultiPolygon类型。

  2. 在ogr2ogr命令中使用-nlt PROMOTE_TO_MULTI选项,将几何类型提升为MultiPolygon。

最终解决方案

以下是最终的解决方案代码,解决了上述所有问题:

关于如何找到'ogr2ogr_path'路径,在我之前的文章中有解释。

python 复制代码
import subprocess



def import_shapefile_to_postgis(shapefile_path, host, dbname, user, password, schema_name, table_name, ogr2ogr_path='ogr2ogr'):

    # 设置PostGIS连接字符串

    connection_string = f"PG:host={host} dbname={dbname} user={user} password={password}"

    

    # 使用subprocess运行ogr2ogr命令,并指定schema

    result = subprocess.run([

        ogr2ogr_path,

        '-f', 'PostgreSQL',

        connection_string,

        shapefile_path,

        '-nln', f'{schema_name}.{table_name}',  # 指定目标schema和表名

        '-lco', f'SCHEMA={schema_name}',        # 指定目标schema

        '-nlt', 'PROMOTE_TO_MULTI',             # 提升几何类型为MultiPolygon

        '-overwrite'                            # 覆盖已存在的表

    ], capture_output=True)



    # 手动解码输出

    stdout = result.stdout.decode('utf-8', errors='replace')

    stderr = result.stderr.decode('utf-8', errors='replace')

    

    # 打印结果

    print("STDOUT:", stdout)

    print("STDERR:", stderr)



if __name__ == "__main__":

    # 设置参数

    shapefile_path = 'STATES.shp'  # 替换为您的shapefile路径

    host = 'localhost'

    dbname = 'gis'

    user = 'lipeijin'

    password = 'password'

    schema_name = 'public'         # 目标schema名称

    table_name = 'states_postgis'  # 确保表名符合PostgreSQL命名规范

    ogr2ogr_path = r'C:\Users\Liai_\anaconda3\envs\geo_env\Library\bin\ogr2ogr.exe'  # 这里设置完整路径



    # 导入Shapefile到PostGIS

    import_shapefile_to_postgis(shapefile_path, host, dbname, user, password, schema_name, table_name, ogr2ogr_path)

QGIS展示

相关推荐
li星野6 小时前
FastAPI 项目加入 WebSocket 支持
python·websocket·fastapi
怪我冷i6 小时前
多租户系统PostgreSQL
数据库·postgresql
lbb 小魔仙6 小时前
2026远程办公软件夏季深度横测:ToDesk、向日葵、网易UU远程全面对比,远控白皮书
android·服务器·网络协议·tcp/ip·postgresql
tangweiguo030519876 小时前
LangGraph 入门:多智能体工作流实战(阿里云百炼)
人工智能·python·langchain
Ares-Wang6 小时前
Flask》》Flask-Caching缓存插件
python·缓存·flask
明如正午6 小时前
转换pdf文件为md文件【markitdown+pdf4llm】
python·pdf·markitdown·pdf4llm
咯哦哦哦哦6 小时前
Foundationpose环境配置【非conda--纯UV】(linux22.04+python3.10)
python·pip·uv
北重楼016 小时前
如何取消一个挂起的 PostgreSQL 查询
数据库·postgresql
AC赳赳老秦6 小时前
项目闭环管理:用 OpenClaw 对接 Jira / 禅道,实现需求 - 任务 - 进度 - 验收全流程自动化
运维·人工智能·python·自动化·devops·jira·openclaw
fillwang6 小时前
间接料库存预警报告设计
python·rpa