我想在python中通过psycopg2调用postgres存储过程后获取一个列名列表...
这是我的代码
# create a connection to the database
conn = psycopg2.connect(...)
# create a cursor object for execution
curs = conn.cursor()
curs.callproc('usp_my_stored_proc', ['mySP'])
# now open a new cursor & "steal" the recordset from the previous cursor
curs2 = conn.cursor('mySP')
# close cursor & connection
curs2.close()
curs.close()
conn.close()
现在我要打印出存储过程的列,并为我的CSV文件制作标题 - 我搜索了一下,但我没有找到任何线索......
建议/帮助绝对值得欢迎......
答案 0 :(得分:2)
两种方式
1)获取一条记录后,curs2.description
将包含名称和类型:
>>> curs.execute("declare cu cursor for select a, a*2 as b from generate_series(1,10) x(a);")
>>> curs2 = cnn.cursor('cu')
>>> curs2.description
>>> curs2.fetchone()
(1, 2)
>>> curs2.description
(Column(name='a', type_code=23, display_size=None, internal_size=4, precision=None, scale=None, null_ok=None),
Column(name='b', type_code=23, display_size=None, internal_size=4, precision=None, scale=None, null_ok=None))
2)检查postgres系统目录:
=# create function my_thing(p1 int, p2 int, out o1 int, out o2 int) returns setof record language sql as $$select a, a*2 from generate_series(p1,p2) x(a)$$;
CREATE FUNCTION
=# select * from my_thing(3,5);
o1 | o2
----+----
3 | 6
4 | 8
5 | 10
=# select proargmodes, proargnames, proallargtypes from pg_proc where proname = 'my_thing';
proargmodes | proargnames | proallargtypes
-------------+---------------+----------------
{i,i,o,o} | {p1,p2,o1,o2} | {23,23,23,23}
有关字段的含义,请参阅pg_proc docs。