从执行存储过程的psycopg2游标中获取列名列表?

问题描述 投票:1回答:1

我想在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文件的标题 - 我已搜索,但我没有找到任何线索......

建议/帮助绝对值得欢迎......

python python-3.x postgresql cursor psycopg2
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.