How to get attributes of a column from a query using PostgreSQL?

I need to get field attributes from a query, for example in this question: How to get a query for column attributes from a table name using PostgreSQL? but for a query, is there a way to do this?

+3


source to share


1 answer


Assuming you are using psycopg2

as your database driver, the field cursor.description

is what you want:

import pprint
import psycopg2
conn = psycopg2.connect('');
curs = conn.cursor()
curs.execute("SELECT 1 as col1, 2 as col2, 'text' as colblah");
pprint.pprint(curs.description)

      

gives:



(Column(name='col1', type_code=23, display_size=None, internal_size=4, precision=None, scale=None, null_ok=None),
 Column(name='col2', type_code=23, display_size=None, internal_size=4, precision=None, scale=None, null_ok=None),
 Column(name='colblah', type_code=705, display_size=None, internal_size=-2, precision=None, scale=None, null_ok=None))

      

Type codes are PostgreSQL internal object identifiers.

For details, see the manualpsycopg2

, which explains how, among other things, to convert types of types to type names.

+5


source







All Articles