Hyp*_*ion 4 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
Run Code Online (Sandbox Code Playgroud)
列名将是字典键。是否有更短的方法来存档相同的结果?20 行变量真的很难看....
您可以传递dictionary=True给游标以使其返回字典。
cursor = cnx.cursor(dictionary=True)
Run Code Online (Sandbox Code Playgroud)
请参阅MySQLCursorDict 上的文档。
| 归档时间: |
|
| 查看次数: |
2280 次 |
| 最近记录: |