MySQL: Get column name or alias from query

后端 未结 10 1725
死守一世寂寞
死守一世寂寞 2020-11-28 20:04

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

相关标签:
10条回答
  • 2020-11-28 20:34

    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]
    
    0 讨论(0)
  • 2020-11-28 20:40

    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)
    
    0 讨论(0)
  • 2020-11-28 20:41

    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)
    )
    
    0 讨论(0)
  • 2020-11-28 20:41

    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
    
    0 讨论(0)
提交回复
热议问题