导入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'路径,在我之前的文章中有解释。
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展示


![[保姆式教程]使用目标检测模型YOLO V5 OBB进行旋转目标的检测:训练自己的数据集(基于卫星和无人机的农业大棚数据集)](https://img-blog.csdnimg.cn/direct/a870017c22e64d27b9bd95e3c5abe108.jpeg)

















