Retrieving Column Names and Quantity from SQL Query in MySQL
In Python programs utilizing MySQLdb, obtaining the column names and count from an SQL query can be challenging. This article aims to provide an accessible solution without the need for manual SQL parsing.
To extract column names, leverage the cursor.description attribute. It returns a tuple of tuples, with each inner tuple's first element representing the column header. The following code demonstrates:
<code class="python">num_fields = len(cursor.description) field_names = [i[0] for i in cursor.description]</code>
This code stores the number of columns in num_fields and the column names in a list called field_names.
To determine the number of columns returned, simply use len(field_names) or num_fields.
In the example provided, with the query:
<code class="sql">select ext, sum(size) as totalsize, count(*) as filecount from fileindex group by ext order by totalsize desc;</code>
The resulting field_names would be:
<code class="python">['ext', 'totalsize', 'filecount']</code>
and num_fields would be 3.
The above is the detailed content of How to Retrieve Column Names and Quantity from SQL Queries in MySQL with Python?. For more information, please follow other related articles on the PHP Chinese website!