首先,确保你的环境已经安装了必要的库。你需要 geopandas, sqlalchemy, psycopg2 (或 psycopg2-binary), 和 geoalchemy2。可以通过以下命令安装:
pip install geopandas sqlalchemy psycopg2-binary geoalchemy2
上代码
python
import geopandas as gpd
from sqlalchemy import create_engine
# 读取Shapefile
gdf = gpd.read_file('./files/par/par.shp')
# 如果需要,转换坐标系统至合适的SRID(例如WGS 84的EPSG:4326)
gdf = gdf.to_crs(epsg=4326)
# 设置编码
# gdf.columns = [col.encode('GBK') for col in gdf.columns]
# 检查当前几何列
print("当前活跃几何列:", gdf._geometry_column_name)
print("所有列:", gdf.columns.tolist())
gdf
try:
db_config = {
"host": "X", # 例如 "localhost"
"port": "5432", # 例如 "5432"
"database": "postgres",
"user": "postgres",
"password": "XX"
}
# 2. 创建SQLAlchemy引擎
# 连接字符串格式:postgresql://用户名:密码@主机:端口/数据库名
engine = create_engine(f'postgresql://{db_config["user"]}:{db_config["password"]}@{db_config["host"]}:{db_config["port"]}/{db_config["database"]}')
# # 导入数据到PostGIS
gdf.to_postgis(
name='传感器数据', # 数据库中目标表名
con=engine,
if_exists='replace', # 表存在时的操作:'replace'替换,'append'追加,'fail'失败
index=True # 不建议将DataFrame索引作为列导入
)
print("数据已成功导入PostGIS!")
except Exception as e:
print(e)
查看结果
可以看到,字段的类型没有完全都转为string
