2017-02-10 23 views
0

我和20列的表,我用這個代碼來獲得特定電影的各個領域作爲詞典:Python的mysql.connector - 正確的方式以檢索行作爲字典

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行變量真的很糟糕....

回答

1

您可以將dictionary=True傳遞給遊標讓它返回字典。

cursor = cnx.cursor(dictionary=True) 

請參閱docs on MySQLCursorDict

0

您可以使用zip到俱樂部的屬性名和值:

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