我有一个SQL语句,其中包含嵌入在ARRAY()中的子查询,如下所示:
SELECT foo, ARRAY(SELECT x from y) AS bar ...
该查询工作正常,但是在psycopg2结果游标中,该数组作为字符串(如“ {1,2,3}”)而不是列表返回.
我的问题是,将像这样的字符串转换为python列表的最佳方法是什么?
解决方法:
它对我有用,无需解析:
import psycopg2
query = """
select array(select * from (values (1), (2)) s);
"""
conn = psycopg2.connect('dbname=cpn user=cpn')
cursor = conn.cursor()
cursor.execute(query)
rs = cursor.fetchall()
for l in rs:
print l[0]
cursor.close()
conn.close()
执行时的结果:
$python *_select_array.py
[1, 2]
更新资料
您需要注册uuid类型:
import psycopg2, psycopg2.extras
query = """
select array(
select *
from (values
('A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A11'::uuid),
('A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A11'::uuid)
)s
);
"""
psycopg2.extras.register_uuid()
conn = psycopg2.connect('dbname=cpn user=cpn')
cursor = conn.cursor()
cursor.execute(query)
rs = cursor.fetchall()
for l in rs:
print l[0]
cursor.close()
conn.close()
结果:
$python *_select_array.py
[UUID('a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11'), UUID('a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11')]