在Python中读取PostgreSQL数组数据



使用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中是否有内置函数?

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]))