How can I retrieve data from MySQL query using column names (I am just using it by index). For example, this is my sample code:
query = ('SELECT Column1 as name, Column2 as lastname, Column 3 as othername FROM '
'table WHERE condition = 1 ORDER BY name ASC LIMIT 1')
cursor.execute(query) # I'll get just 1 result
results = cursor.fetchall()
if not results:
connection.close()
..
else:
for row in results:
var = row[0] # <- Here is the problem, I am using the index to retrieve
# the result from query, I wanna to use 'var = row["name"]' instead
# but this throw me an error because row must be integer type
...
I hope that you can help me. Thank you, have a good day.
Hey in order to use 'row["name"]', you will need to make a dictionary of the query. This can be done by using a dictcursor ...
cursor = connection.cursor(pymysql.cursors.DictCursor) cursor.execute(query)
Hope this helps :)