gpt4 book ai didi

python - 从 SELECT 中简洁地检索许多变量

转载 作者:行者123 更新时间:2023-11-29 03:10:26 26 4
gpt4 key购买 nike

我有一个大约有 50 列的表。要从我正在做的表中检索变量:

cursor.execute("SELECT * FROM title WHERE vendor_id = '%s'"%vendor_id)
data=cursor.fetchone()
provider, language, type, subtype, vendor_id = data[0], data[1], data[2], data[3], data[4]
etc...

有没有办法更简洁地做到这一点:我要定义的变量也是列的名称。也许像(在伪代码中)——

values=cursor.fetchone; columns=cursor.fetchcolumns()
data = zip(columns, values)

最佳答案

select * 在这里特别具有挑战性,因为您不知道哪些列以何种顺序返回。根据您使用的数据库和您使用的包装器,您应该能够将您的行检索为字典,而不是允许您将列引用为行中的字典键。

例如,MySQLdb 通过 DictCursor 支持这一点。参见 http://www.kitebird.com/articles/pydbapi.html

对于其他图书馆,他们应该提供类似的功能。

关于python - 从 SELECT 中简洁地检索许多变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9370175/

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