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展示

相关推荐
默_笙4 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
qq_426003964 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫4 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技4 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读4 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
只睡四小时4 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
奇思妙想聪明勤奋的小羊4 天前
DeepAgents第5章:子Agent 与上下文隔离—让 Agent学会委派
人工智能·python·学习·语言模型
lpfasd1234 天前
2026年第38周GitHub趋势周报
python·科技·github
IZero074 天前
Jev 与 Laya
python·语言模型
geovindu4 天前
sql: Transaction & Concurrency Patterns using postgresql 18
postgresql·数据库开发·数据库架构