Home > Database > Mysql Tutorial > How to Retrieve SQL Result Column Values by Name in Python?

How to Retrieve SQL Result Column Values by Name in Python?

Barbara Streisand
Release: 2024-11-12 10:30:02
Original
803 people have browsed it

How to Retrieve SQL Result Column Values by Name in Python?

Retrieving SQL Result Column Values by Name in Python

Python's database API provides various means to access SQL result column values. While retrieving values based on column indices is the common approach, this method can become cumbersome in scenarios with numerous columns.

For ease of use, Python offers an alternative solution: the DictCursor. This cursor type enables you to access result values by column name, much like Java's get(String columnName) construct.

Implementation using MySQL

To utilize the DictCursor with MySQL using the MySQLdb module:

import MySQLdb

cursor = conn.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("SELECT name, category FROM animal")
result_set = cursor.fetchall()

for row in result_set:
    print("%s, %s" % (row["name"], row["category"]))
Copy after login

Extension to PyMySQL

As per user feedback, the DictCursor functionality is also supported by the PyMySQL module. Simply instantiate a DictCursor instance and access column values via their names.

The above is the detailed content of How to Retrieve SQL Result Column Values by Name in 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