使用Python将点插入PostGIS


Answers:


21

首先,安装psycopg2软件包,这是PostgreSQL的Pythonic接口。

然后,使用ST_MakePoint

>>> import psycopg2
>>> conn = psycopg2.connect(dbname=..., port=..., user=...,
                            password=..., host=...)
>>> cur = conn.cursor()
>>> x, y, z, = 32, 34, 0
>>> cur.execute("SELECT ST_SetSRID(ST_MakePoint(%s, %s, %s),4326);", (x, y, z))
>>> cur.fetchall()
[('01010000A0E6100000000000000000404000000000000041400000000000000000',)]

ST_AsText 可用于验证值:

>>> cur.execute("SELECT ST_AsText(ST_SetSRID(ST_MakePoint(%s, %s, %s),4326));", (x, y, z))
>>> cur.fetchall()
[('POINT Z (32 34 0)',)]

笔记

  • 请记住,(lat, lon)(y, x)不是(x, y)
  • 始终使用参数而不是字符串操作来防止SQL注入。在此示例中,我们(x, y, z)在最后对元组psycopg2进行了处理,以便可以处理替换。

20

对于更复杂的几何图形(例如LineString和Polygon几何图形),可以使用Shapely处理它们,然后将它们作为十六进制编码的WKB通过psycopg2传递。请注意,需要使用Shapely 1.3或更高版本才能通过该wkb_hex属性处理3D几何图形的导出。

import psycopg2
from shapely.geometry import LineString
from shapely import wkb

conn = psycopg2.connect('...')
curs = conn.cursor()

# Make a Shapely geometry
ls = LineString([(2.2, 4.4, 10.2), (3.3, 5.5, 8.4)])
ls.wkt  # LINESTRING Z (2.2 4.4 10.2, 3.3 5.5 8.4)
ls.wkb_hex  # 0102000080020000009A999999999901409A999999999911406666666666662440666666...

# Send it to PostGIS
curs.execute('CREATE TEMP TABLE my_lines(geom geometry, name text)')
curs.execute(
    'INSERT INTO my_lines(geom, name)'
    'VALUES (ST_SetSRID(%(geom)s::geometry, %(srid)s), %(name)s)',
    {'geom': ls.wkb_hex, 'srid': 4326, 'name': 'First Line'})

conn.commit()  # save data

# Fetch the data from PostGIS, reading hex-encoded WKB into a Shapely geometry
curs.execute('SELECT name, geom FROM my_lines')
for name, geom_wkb in curs:
    geom = wkb.loads(geom_wkb, hex=True)
    print('{0}: {1}'.format(name, geom.wkt))
# First Line: LINESTRING Z (2.2 4.4 10.2, 3.3 5.5 8.4)

还要注意,可以通过发送几何的WKT来完成类似的操作,但是由于将其转换为文本,因此它是有损的,并且可能会降低精度的埃。以十六进制编码的WKB传输几何是无损的,并保留了每个坐标的精确度。


非常好,谢谢!我想知道这两种方法之间是否存在性能差异。
亚当·马坦

使用构建点有10%的性能优势ST_MakePoint,这对于点几何非常有用。但是,使用Shapely通常可以更简单地构建更复杂的几何类型。
Mike T
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.