【发布时间】:2020-07-26 07:21:31
【问题描述】:
我正在使用带有 postgis 扩展的 postgres 数据库。我必须使用 python 作为后端将数据插入到 postgres 中。我正在使用 psycopg2 进行连接,我的 python 版本是 3.7 。我无法推送我的数据,因为 python 一直在转义字符串文字。以下是我的代码。
def insert(lvalues):
lvalues = [str(i) for i in lvalues]
values = ', '.join(lvalues)
return values
if __name__ == '__main__':
cursor, conn = connect()
cord = [
[
[
67.774658203125,
25.69103802005013
],
[
68.90625,
24.367113562651262
],
[
73.970947265625,
25.958044673317843
],
[
74.87182617187499,
28.565225490654658
],
[
70.33447265624999,
28.815799886487298
],
[
67.774658203125,
25.69103802005013
]
]
]
js = insert(('GISid', 'srid', 'familyid', 'geom', 'nameofgeom'))
jst = '''{ "type": "Polygon","coordinates": ''' + str(cord) + ''',
"crs": {"type": "name", "properties": {"name": "EPSG:4326"}}
}'''
print(cursor.mogrify(
"INSERT INTO public.spatial_data(gid, srid, familyid, geom, nameofgeom) VALUES (103,4326,2,ST_GeomFromGeoJSON(%s),'polygon') ",
(jst,)))
我得到的结果如下:
b'INSERT INTO public.spatial_data(gid, srid, familyid, geom, nameofgeom) VALUES (103,4326,2,ST_GeomFromGeoJSON(\'{ "type": "Polygon","coordinates": [[[67.774658203125, 25.69103802005013], [68.90625, 24.367113562651262], [73.970947265625, 25.958044673317843], [74.87182617187499, 28.565225490654658], [70.33447265624999, 28.815799886487298], [67.774658203125, 25.69103802005013]]],\n "crs": {"type": "name", "properties": {"name": "EPSG:4326"}}\n }\'),\'polygon\') '
有人可以建议一种删除 mogrify 结果中出现的 \ 和 \n 的方法。 cursor 是 psycopg2 连接游标对象。 提前谢谢你。
【问题讨论】:
标签: python-3.x geospatial postgis