Home > Database > Mysql Tutorial > body text

How to Retrieve Column Names and Quantity from SQL Queries in MySQL with Python?

Susan Sarandon
Release: 2024-11-05 16:36:02
Original
314 people have browsed it

How to Retrieve Column Names and Quantity from SQL Queries in MySQL with Python?

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>
Copy after login

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>
Copy after login

The resulting field_names would be:

<code class="python">['ext', 'totalsize', 'filecount']</code>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template