3

I use Mysql Connection in Python script.

How can I get results from table by names?

cursor = conn.cursor()
cursor.execute("SELECT * FROM local")

Now I do this by index:

results = cursor.fetchall()
for row in results:
   print row[0] //

Instead that I wanna get fields by names like as: print row["name"]

2

3 Answers 3

11

If you are using mysql-connector, Try this

cursor = conn.cursor(dictionary=True)
cursor.execute("SELECT * FROM myTable")
results = cursor.fetchall()
for row in results:
    print( row )

If dictionary is True, the cursor returns rows as dictionaries.

Sign up to request clarification or add additional context in comments.

2 Comments

You Sir deserve a medal. 2 hours of research on Internet, no solutions works except yours ! Fast, small, clean. Thanks so much. I upvoted you obviously.
I second the medal: Hero Pythonista First Class.
4

Instead you can use pandas library

import pandas as pd
sql = "SELECT * FROM local"
df = pd.read_sql(sql,conn)

for index,row in df.iterrows():
    print(row['name'])

I hope this helps

2 Comments

How to install pandas in Cent OS?
pip install pandas
-1

If you are using the MySQLdb for python you can transmit to your cursor instance a DictCursor.

Here is a full example using MySQLdb:

>>> import MySQLdb
>>> db = MySQLdb.connect(host="localhost",user="test",passwd="test",db="test")
>>> cursor = db.cursor(MySQLdb.cursors.DictCursor)
>>> cursor.execute("SELECT * FROM test_user")
2
>>> results = cursor.fetchall()
>>> for result in results:
...    print(result["username"])
test1
test2

Hope it's useful.

Also, you can find answers here suitable for your tuple situation. python mysql.connector DictCursor?

4 Comments

It does not work "TypeError: tuple indices must be integers, not str"
What module for mysql are you using ?
import mysql.connector
For mysql connector, use the answer from @Anoop

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.