【问题标题】:Get a list of column names from a psycopg2 cursor executing stored proc?从执行存储过程的 psycopg2 游标中获取列名列表?
【发布时间】:2018-02-28 01:42:56
【问题描述】:

在 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】:

    两种方式

    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

    【讨论】:

      猜你喜欢
      • 2012-05-02
      • 1970-01-01
      • 2011-06-25
      • 2018-09-21
      • 2023-04-11
      • 1970-01-01
      • 2023-03-04
      • 1970-01-01
      相关资源
      最近更新 更多