Psycopg ppygis select 查询

Psycopg ppygis select query

我正在尝试使用 python ppygis 包设置一个基本的工作 postgis 设置。

>>> import psycopg2
>>> import ppygis
>>> connection = psycopg2.connect(database='spre', user='postgres')
>>> cursor = connection.cursor()
>>> cursor.execute('CREATE TABLE test (geometry GEOMETRY)')
>>> cursor.execute('INSERT INTO test VALUES(%s)', (ppygis.Point(1.0, 2.0),))
>>> cursor.execute('SELECT * from test')
>>> point = cursor.fetchone()[0]
>>> print point
0101000000000000000000F03F0000000000000040
>>>

我应该得到一个 python 具有独立 X 和 Y 坐标的对象。像

>>> Point(X: 1.0, Y: 2.0)

我做错了什么?

你没有做错任何事。按照问题 (010100...) 中所示的 the same steps as the PPyGIS basic example, I get the same hex-encoded EWKB,这通常是预期的。也许这适用于旧版本的 PPyGIS / Psycopg?今天没有。

这个包似乎没有正确地将自己注册为 PostGIS 类型的适配器,所以我的建议是不要使用这个包。此外,您不需要额外的包来使用 Psycopg2 中的 PostGIS。


这是 read/write 点的正常方法,没有任何额外的包:

# Assuming PostGIS 2.x, use a typmod
cursor.execute('CREATE TEMP TABLE test (geom geometry(PointZ,4326));')
# Longyearbyen, 78.22°N 15.65°E, altitude 10 m
cursor.execute('''\
    INSERT INTO test (geom)
    VALUES(ST_SetSRID(ST_MakePoint(%s, %s, %s), 4326));
''', (15.65, 78.22, 10.0))
cursor.execute('''\
    SELECT ST_Y(geom) AS latitude, ST_X(geom) AS longitude, ST_Z(geom) AS altitude
    FROM test;
''')
print(cursor.fetchone())  # (78.22, 15.65, 10.0)
cursor.execute('SELECT ST_AsText(geom) FROM test;')
print(cursor.fetchone()[0])  # POINT Z (15.65 78.22 10)
cursor.execute('SELECT ST_AsLatLonText(geom) FROM test;')
print(cursor.fetchone()[0])  # 78°13'12.000"N 15°39'0.000"E

如果您希望客户端的几何对象对实际几何做更多的工作,请考虑使用 Shapely,它可以使用 WKB 数据连接:

from shapely.wkb import loads
cursor.execute('SELECT geom FROM test;')
pt = loads(cursor.fetchone()[0], hex=True)
print(pt)  # POINT Z (15.65 78.22 10)