在 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 文件制作它们的标题 - 我已经搜索但没有找到任何线索......
绝对欢迎建议/帮助...
最佳答案
两种方式
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字段的含义。
关于python - 从执行存储过程的 psycopg2 游标获取列名列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49020718/