How do I get the column names from a row returned from an adodbapi query?

Cheeso picture Cheeso · Mar 17, 2012 · Viewed 26.1k times · Source

Suppose I query a database like this :

import adodbapi
conn = adodbapi.connect(connStr)
tablename = "[salesLT].[Customer]"

cur = conn.cursor()

sql = "select * from %s" % tablename
cur.execute(sql)

result = cur.fetchall()

The result is, I think, a sequence of SQLrow objects.

How can I get a list or sequence of the column names returned by the query?

I think it is something like this:

    row = result[0]
    for k in row.keys():
        print(k)

...but .keys() is not it.

nor .columnNames()

Answer

mechanical_meat picture mechanical_meat · Mar 17, 2012

cur.description is a read-only attribute containing 7-tuples that look like:

(name, 
type_code, 
display_size,
internal_size, 
precision, 
scale, 
null_ok)

So for column names you might do:

col_names = [i[0] for i in cur.description]

Reference: http://www.python.org/dev/peps/pep-0249/