java
java

Reputation: 1214

Get row values from MySQL

I'm following this guide: https://scriptingmysql.wordpress.com/2011/09/09/retrieving-data-from-mysql-via-python/

This is the code:

...
cursor.execute ("SELECT X,Y,Z FROM tab_a")

# fetch all of the rows from the query
data = cursor.fetchall()

# print the rows
for row in data :
   print row[0]

This doesn't work. It says:

print row[0]
KeyError: 0

if I change it to:

for row in data :
   print row

it gives:

 {'X: '120', 'Y': '0', 'Z': '730'}

This is the correct data but I want it to print only 120 not the whole list.

How do I do that?

Upvotes: 1

Views: 493

Answers (1)

Padraic Cunningham
Padraic Cunningham

Reputation: 180401

Adding cursor(MySQLdb.cursors.DictCursor) means you get a dict returned in place of the tuples you would normally get so you need to access by key:

for row in data:
    print(row["X"])

Upvotes: 1

Related Questions