title: MySQL: Get column name or alias from query
body: <p>I'm not asking for the <code>SHOW COLUMNS</code> command.</p>
  
  <p>I want to create an application that works similarly to heidisql, where you can specify an SQL query and when executed, returns a result set with rows and columns representing your query result. The column names in the result set should match your selected columns as defined in your SQL query.</p>
  
  <p>In my Python program (using <code>MySQLdb</code>) my query returns only the row and column results, but not the column names.  In the following example the column names would be <code>ext</code>, <code>totalsize</code>, and <code>filecount</code>.  The SQL would eventually be external from the program. </p>
  
  <p>The only way I can figure to make this work, is to write my own SQL parser logic to extract the selected column names.</p>
  
  <p>Is there an easy way to get the column names for the provided SQL?
  Next I'll need to know how many columns does the query return?</p>
  
  <pre><code># Python
  
  import MySQLdb
  
  #===================================================================
  # connect to mysql
  #===================================================================
  
  try:
      db = MySQLdb.connect(host="myhost", user="myuser", passwd="mypass",db="mydb")
  except MySQLdb.Error, e:
      print "Error %d: %s" % (e.args[0], e.args[1])
      sys.exit (1)
  
  #===================================================================
  # query select from table
  #===================================================================
  
  cursor = db.cursor ()   
  
  cursor.execute ("""\
       select ext,
          sum(size) as totalsize,
          count(*) as filecount
       from fileindex
      group by ext
      order by totalsize desc;
  """)
  
  while (1):
      row = cursor.fetchone ()
      if row == None:
          break
      print "%s %s %s\n" % (row[0], row[1], row[2])
  
  cursor.close()
  db.close()      
  </code></pre>