数据格式:
创建test数据库
注意要选择postgis范本
执行代码
import psycopg2
from psycopg2.extras import RealDictCursor
from shapely.wkt import dumps
from shapely.geometry import Polygon# 数据
data = [{'name': 'a','geom':'104.059962,30.647005;104.06156,30.649142;104.062694,30.650745;104.063921,30.652742;104.064346,30.652746;104.064561,30.652686;104.065495,30.652663;104.059962,30.647005',},{'name': 'b','geom':'104.236258,30.686956;104.234757,30.687411;104.233716,30.687536;104.232814,30.687523;104.231929,30.687296;104.231295,30.686936;104.230775,30.686467;104.229629,30.685142;104.229014,30.684482;104.22838,30.683951;104.227979,30.683657;104.227813,30.683835;104.227269,30.684107;104.227149,30.684118;104.226463,30.684118;104.225964,30.684232;104.225459,30.684294;104.236258,30.686956',},
]# 连接PostgreSQL数据库
connection = psycopg2.connect(dbname="test",user="postgres",password="user",host="localhost", # 请替换为实际数据库服务器地址port="5432"
)# 创建游标对象
cursor = connection.cursor(cursor_factory=RealDictCursor)# 创建表(如果不存在)
cursor.execute("""CREATE TABLE IF NOT EXISTS keshan (id SERIAL PRIMARY KEY,name VARCHAR(255),geom GEOMETRY(POLYGON, 4326));
""")# 清空keshan表(如果已存在)
cursor.execute("""DELETE FROM keshan;ALTER SEQUENCE keshan_id_seq RESTART WITH 1; -- 重置id序列
""")# 将polyline转换为Polygon对象
def polyline_to_polygon(polyline):points = [(float(x), float(y)) for x, y in [p.split(',') for p in polyline.split(';')]]return Polygon(points)# 插入数据
for district in data:polygon = polyline_to_polygon(district['geom'])wkt = dumps(polygon, rounding_precision=6)# 插入记录cursor.execute("""INSERT INTO keshan (name, geom) VALUES (%s, ST_GeomFromText(%s, 4326))""", (district['name'], wkt))# 提交事务
connection.commit()# 关闭游标和连接
cursor.close()
connection.close()