我有一个函数,它每年获取一位董事的所有数据,但是我必须为每年创建一个新函数才能将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]
答案 0 :(得分:0)
是的,这很简单。基本思路是使用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.
我希望这会有所帮助!