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.
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"]))
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!