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

标签 python python-3.x postgresql cursor psycopg2

在 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/

相关文章:

python - 如何从pyodbc中的用户获取表名,同时避免SQL注入(inject)?

python - 将数据附加到 Pandas 全局数据框变量不会持久

python-3.x - 根据优先级修改数据框

python - 如何计算基于多级索引的时间戳差异?

Python 正则表达式搜索 : repeated digit n times

java - Postgres DB 触发器调用 Java 函数

避免指针的 Pythonic 方法

python - 根据多个条件获取 NumPy 数组的连续元素组

php - 在 postgresql PDO 连接中设置连接超时参数

java - 如何在数据库属性文件中获取用户名和密码的值而不是 hibernate.cfg.xml