I've a table with 20 columns, I use this code to get every field of a specific movie as a dictionary:
import mysql.connector
def getMovie(id):
movie = {}
cnx = mysql.connector.connect(**config)
cursor = cnx.cursor()
query = ('SELECT * FROM movies WHERE id = %s') % id
cursor.execute(query)
for row in cursor:
movie['id'] = row[0]
movie['actors'] = row[1]
movie['title'] = row[2]
# and so on for 20 lines
return movie
Column names would be the dictionary keys. Is there a shorter way to archive the same result? 20 lines of variables are really bad looking....
You can pass dictionary=True
to the cursor to get it to return a dictionary.
cursor = cnx.cursor(dictionary=True)
See the docs on MySQLCursorDict.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With