Python mysql.connector - 将行作为字典进行检索的正确方法

时间:2017-02-10 17:23:24

标签: python mysql dictionary

我有一个包含20列的表格,我使用此代码将特定电影的每个字段作为字典:

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

列名称将是字典键。是否有更短的方式来存档相同的结果? 20行变量看起来很糟糕......

2 个答案:

答案 0 :(得分:3)

您可以将dictionary=True传递给光标以使其返回字典。

cursor = cnx.cursor(dictionary=True)

请参阅docs on MySQLCursorDict

答案 1 :(得分:0)

您可以使用zip将您的属性名称和值标记为:

attribute_names = ["id", "actors", "title"]
values = [10, 20, 30] # row in your case
d = dict(zip(attribute_names, values))