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"]

Chris_Rands
  • 38,994
  • 14
  • 83
  • 119
Goga
  • 405
  • 1
  • 6
  • 13

3 Answers3

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.

mike rodent
  • 14,126
  • 11
  • 103
  • 157
Anoop
  • 2,748
  • 4
  • 18
  • 27
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

Aakash Makwana
  • 734
  • 5
  • 9
-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?

Community
  • 1
  • 1