在Python中读取PostgreSQL数组数据

2024-09-30 14:22:09 发布

您现在位置:Python中文网/ 问答频道 /正文

在使用Python的psycopg2进行查询之后

SELECT 
    id,
    array_agg(еnty_pub_uuid) AS ptr_entity_public 
FROM table
GROUP BY id

我得到一个数组:

{a630e0a3-c544-11ea-9b8c-b73c488956ba,c2f03d24-2402-11eb-ab91-3f8e49eb63e7} 

如何用python将其解析为列表

psycopg2中是否有内置函数


Tags: fromiduuidastablegrouppublicarray
2条回答

psycopg2关心python和postgres之间的类型对话:

import psycopg2

conn = psycopg2.connect("...")
cur = conn.cursor()
cur.execute(
    "select user_id, array_agg(data_name) from user_circles where user_id = '81' group by user_id"
)
res = cur.fetchall()
print(res[0])
print(type(res[0][1]))

输出:

('81', ['f085b2e3-b943-429e-850f-4ecf358abcbc', '65546d63-be96-4711-a4c1-a09f48fbb7f0', '81d03c53-9d71-4b18-90c9-d33322b0d3c6', '00000000-0000-0000-0000-000000000000'])
<class 'list'>

您需要为python和postgres注册UUID类型以推断类型


import psycopg2.extras
psycopg2.extras.register_uuid()
sql = """
SELECT 
    id,
    array_agg(еnty_pub_uuid) AS ptr_entity_public 
FROM table
GROUP BY id
"""
cursor = con.cursor()
cursor.execute(sql)
results = cursor.fetchall()

for r in results:
    print(type(r[1]))

相关问题 更多 >