Python 读取PostgreSQL的geometry字段时,获取geometry的中心点
    		       		warning:
    		            这篇文章距离上次修改已过423天,其中的内容可能已经有所变动。
    		        
        		                
                
import psycopg2
from psycopg2.extras import RealDictCursor
 
# 连接PostgreSQL数据库
conn = psycopg2.connect(
    dbname="your_db_name", 
    user="your_username", 
    password="your_password", 
    host="your_host"
)
 
# 创建游标对象
cur = conn.cursor(cursor_factory=RealDictCursor)
 
# 执行SQL查询语句,获取geometry对象的中心点
cur.execute("""
    SELECT ST_X(ST_Centroid(your_geometry_column::geometry)) AS long,
           ST_Y(ST_Centroid(your_geometry_column::geometry)) AS lat
    FROM your_table
    WHERE your_conditions
""")
 
# 获取查询结果
rows = cur.fetchall()
 
# 打印中心点坐标
for row in rows:
    print(f"Longitude: {row['long']}, Latitude: {row['lat']}")
 
# 关闭游标和连接
cur.close()
conn.close()确保替换your_db_name, your_username, your_password, your_host, your_geometry_column, 和 your_table为你的实际数据库信息和表名。your_conditions是你的查询条件,根据需要替换。
评论已关闭