我正在使用以下 SQL 代码更新包含几何图形的表,并使用 pgadmin 中的查询工具进行工作:
INSERT INTO mytable (id, geometry) VALUES (1, ST_SetSRID(ST_GeomFromText('Point(15.5 17.7)'),4326), < more tuples >
ON CONFLICT (id) DO UPDATE
geometry = EXCLUDED.geometry
我想使用此代码使用 psycopg2 从 Python 进行批量更新插入。
# Mock code:
# Prepare geodataframe for upsert:
points = ["ST_SetSRID(ST_GeomFromText('Point({} {})', 4326)".format(geo.x, geo.y) for geo in gdf.geometry]
gdf = gdf.assign(points=points)
upsert_tuples = [tuple(x) for x in gdf[['points', 'id', <other relevant cols>]].to_numpy()]
# SQL code
upsert_sql = '''INSERT INTO mytable (geometry, id, <other cols>) VALUES %s
ON CONFLICT (id) DO UPDATE SET
geometry = EXCLUDED.geometry,
<other = etc>;'''
# Connect to database
...
extras.execute_values(cursor, upsert_sql, upsert_tuples)
...
这会引发错误消息:
parse error - invalid geometry
。如何从 Python 更新插入几何图形?