I'm trying to get a list of column names after calling my postgres stored proc via psycopg2 in python...
Here's my code
# 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()
Now I want to print out the columns of my stored proc and make them headers for my CSV file - I've search and I haven't found any leads...
Advice / Help is definitely welcome...
Two ways
1) after fetching one record, curs2.description
will contain names and types:
>>> 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) inspect the postgres system catalog:
=# 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}
See pg_proc docs for the meaning of the fields.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.