Goga
Goga

Reputation: 425

How to get fields by name in query Python?

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

Upvotes: 3

Views: 7692

Answers (3)

Anoop
Anoop

Reputation: 2798

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.

Upvotes: 11

Banuta Alin Alexandru
Banuta Alin Alexandru

Reputation: 113

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?

Upvotes: -1

Aakash Makwana
Aakash Makwana

Reputation: 754

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

Upvotes: 4

Related Questions