gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 04:35:52 24 4
gpt4 key购买 nike

我有一个包含 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行变量真难看....

最佳答案

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

cursor = cnx.cursor(dictionary=True)

参见 docs on MySQLCursorDict .

关于Python mysql.connector - 将行作为字典检索的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42165218/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com