Python MySQL Connector fetchone not returning dict

Viewed 460

I have a table of users that I want to display in a flask app. I've been trying to get the values to print out in the console but I can't seem to figure out how to do that using the key (i.e. the field name). I have the following:

cur = CONN.cursor()
cur.execute("SELECT * FROM users")
users = cur.fetchone()

print(users)

Output is:

(1, 0, 'James', 'Brubacker', 'Anaheim', 1)

When I do:

print(users['first_name'])

I get:

TypeError: tuple indices must be integers or slices, not str

I was under the assumption that fetchone() returned a dict by default but it doesn't. How can I get it to return a dict?

2 Answers

No, fetchone by default returns a tuple. That's a part of the dbAPI standard. You can say cur = CONN.cursor(dictionary=True), as described in the fine documentation.

fetchone() and fetchall() return tuple not the dicts by default. To access the data in tuple, you should use index if you want to retrieve the first element then do row[0] and you can access via users['first_name'].

If you need to get the result as dict, make use of any one of following option,

Option1

Add the parameter cursorclass=MySQLdb.cursors.DictCursor at the end of your MySQLdb.connect.

Sample

conn = MySQLdb.connect(host="host",
                        user="username",
                        passwd="password",
                        db="databasename", 
                        cursorclass=MySQLdb.cursors.DictCursor)

Option 2

Update connection to return the dict

Sample

 cur = CONN.cursor(dictionary=True)
    cur.execute("SELECT * FROM users")
    users = cur.fetchone()
    print(users['first_name'])
Related