Is there a way to retrieve SQL result column value using column name instead of column index in Python? I\'m using Python 3 with mySQL. The syntax I\'m looking for is pretty
The MySQLdb module has a DictCursor:
Use it like this (taken from Writing MySQL Scripts with Python DB-API):
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"])
edit: According to user1305650 this works for pymysql as well.
import mysql.connector as mysql
...
cursor = mysql.cnx.cursor()
cursor.execute('select max(id) max_id from ids')
(id) = [ id for id in cursor ]
you must look for something called " dictionary in cursor "
i'm using mysql connector and i have to add this parameter to my cursor , so i can use my columns names instead of index's
db = mysql.connector.connect(
host=db_info['mysql_host'],
user=db_info['mysql_user'],
passwd=db_info['mysql_password'],
database=db_info['mysql_db'])
cur = db.cursor()
cur = db.cursor( buffered=True , dictionary=True)
python 2.7
import pymysql
conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='password', db='sakila')
cur = conn.cursor()
n = cur.execute('select * from actor')
c = cur.fetchall()
for i in c:
print i[1]