7

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()

Cheeso
  • 189,189
  • 101
  • 473
  • 713

3 Answers3

21

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/

mechanical_meat
  • 163,903
  • 24
  • 228
  • 223
0

q=conn.execute("SELECT * FROM YOUR_TABLE") pd.DataFrame.from_records(q.fetchall(),columns=q.keys())

  • Can you clarify how this answers the question? This looks like you're using Pandas (which wasn't part of the original question) and also unclear how your answer satisfies what the OP (from 8+ years ago) was looking for. – Foon Feb 02 '21 at 20:05
0

There is a columnNames property on the collection of SQLrow objects.

So,

for k in result.columnNames:
    print(k)
Cheeso
  • 189,189
  • 101
  • 473
  • 713