python - 有没有办法我可以创建一个 for 循环,遍历不同的值以在 sqlite3 查询中搜索
问题描述
我有一个函数可以每年获取导演的所有数据,但我必须为每年创建一个新函数以将其更改year_granted
为下一年或上一年。有没有一种方法可以制作一个只使用一个函数并将其更改year_granted
为下一年的循环。
def getDirectorsInfo2019(self):
c.execute('SELECT first_name, last_name, year_granted, app_units_granted,
full_value_units_granted
FROM Directors INNER JOIN DirectorsUnits ON DirectorsUnits.id_number_unit =
Directors.id_number_dir
WHERE id_number_dir BETWEEN 1 AND 50 AND year_granted=2019')
datas = c.fetchall()
for people in data:
people = [datas[0]]
for people2 in [datas[0]]:
peopl02 = list(pepl2)
self.firstNAme = people2[0]
self.year2019 = people2[2]
self.lastNAme = people2[1]
self.aUnits2019 = people2[3]
self.fUnits2019 = people2[4]
解决方案
是的,这很简单。基本思想是循环一个范围并使用 DB-API 的“参数替换”方法填写 sql 查询。它看起来像这样:
query = """
SELECT first_name, last_name, year_granted, app_units_granted, full_value_units_granted FROM Directors
INNER JOIN DirectorsUnits ON DirectorsUnits.id_number_unit = Directors.id_number_dir
WHERE id_number_dir BETWEEN 1 AND 50 AND year_granted=?
"""
# I used a triple-quote string here so that the line breaks are ignored
# Note that this loop would fetch data for 1998, 1999, 2000, and 2001, but not 2002
for year in range(1998, 2002):
# Parameter substitution takes a list or tuple of values, so the value must be in a list even though there's only one
rows = c.execute(query, [str(year),]).fetchall()
for row in rows:
#strictly speaking, you don't need these variable assignments, but it helps to show what's going on
first_name = row[0]
last_name = row[1]
year = row[3]
a_units = row[4]
f_units = row[5]
# do stuff with row data here, append to a list, etc.
我希望这有帮助!
推荐阅读
- python-3.x - 我应该使用 matplotlib 中的哪种绘图?
- php - php chilkat_9_5_0 扩展在 Windows 10 中不起作用
- swift - AppAuth 的弃用警告
- php - 如何通过php在json记录中显示office的值
- git - 如何将远程分支克隆到已经存在的本地存储库中?
- c# - 是否可以将构造函数注入与泛型类型一起使用?
- antlr - Antlr3 具有良好 AST 的表达式的非递归/左分解语法
- javascript - 无法在页面上居中 Slick Carousel
- javascript - 在 React 中使用 2 个下拉菜单。无法读取未定义的属性“地图”
- java - JVM 如何在屏幕上打印一些东西?