I\'m not asking for the SHOW COLUMNS
command.
I want to create an application that works similarly to heidisql, where you can specify an SQL query and w
cursor.description will give you a tuple of tuples where [0] for each is the column header.
num_fields = len(cursor.description)
field_names = [i[0] for i in cursor.description]
This is the same as thefreeman but more in pythonic way using list and dictionary comprehension
columns = cursor.description
result = [{columns[index][0]:column for index, column in enumerate(value)} for value in cursor.fetchall()]
pprint.pprint(result)
Similar to @James answer, a more pythonic way can be:
fields = map(lambda x:x[0], cursor.description)
result = [dict(zip(fields,row)) for row in cursor.fetchall()]
You can get a single column with map over the result:
extensions = map(lambda x: x['ext'], result)
or filter results:
filter(lambda x: x['filesize'] > 1024 and x['filesize'] < 4096, result)
or accumulate values for filtered columns:
totalTxtSize = reduce(
lambda x,y: x+y,
filter(lambda x: x['ext'].lower() == 'txt', result)
)
You can also do this to just get the field titles:
table = cursor.description
check = 0
for fields in table:
for name in fields:
if check < 1:
print(name),
check +=1
check =0