【发布时间】:2021-08-27 21:43:40
【问题描述】:
我正在尝试根据用户的选择从数据库中获取每月值并将它们可视化。 我有复选框,如下所示;
为了根据用户的选择获取每月销售数字,我从复选框中获取值并创建一个新列表,其中仅包含不等于零的值。之后,我编写了一个 Select 查询,其中特定列具有列表中的任何值。但是用户只能选择 1 个值或 3 个值或其他任何值,我的 sql 查询必须根据它进行更改。如果用户选择 1 个值,我必须在我的查询中只使用 1 个“%s”,如果他们选择 5 个值,我必须使用其中的 5 个。所以我创建了一堆 if 函数,其中条件是列表的长度。有没有办法根据列表的长度来安排sql查询中的变量数量?
def plot(self):
self.listo=[]
for val in self.lili:
# self.lili is a list that has all of the checkboxes value in it. Unchecked box values is 0 for all.Checked box values is changing based on month.
val=val.get()
if val !=0:# I created a empty list and add all the checked values in it.
self.listo.append(val)
else:
pass
self.tryn=len(self.listo)# I get the lenght of checked checkboxes.
if self.tryn==0:#If anything is selected it's an error.
messagebox.showerror("Error", "You have to choose at least one")
if self.tryn==1:##If 1 values is selected use this query with 1 variable.
self.cursor.execute("SELECT SUM(current_sales) FROM targets WHERE nameofmonth=(%s)",(self.listo[0],))
self.current_sales1=self.cursor.fetchall()[0][0]
self.cursor.execute("SELECT SUM(target_sales) FROM targets WHERE nameofmonth=(%s)",(self.listo[0],))
self.target_sales1=self.cursor.fetchall()[0][0]
self.show_plot()
if self.tryn==2:##If 2 values is selected use this query with 2 variable.
query=("SELECT SUM(target_sales) FROM targets WHERE (nameofmonth=(%s) OR nameofmonth=(%s))")
self.cursor.execute(query,self.listo)
self.target_sales1=self.cursor.fetchall()[0][0]
query2=("SELECT SUM(current_sales) FROM targets WHERE (nameofmonth=(%s) OR nameofmonth=(%s))")
self.cursor.execute(query2,self.listo)
self.current_sales1=self.cursor.fetchall()[0][0]
self.show_plot()
if self.tryn==3:
query=("SELECT SUM(target_sales) FROM targets WHERE (nameofmonth=(%s) OR nameofmonth=(%s)) OR nameofmonth=(%s)")
self.cursor.execute(query,self.listo)
self.target_sales1=self.cursor.fetchall()[0][0]
query2=("SELECT SUM(current_sales) FROM targets WHERE (nameofmonth=(%s) OR nameofmonth=(%s)) OR nameofmonth=(%s)")
self.cursor.execute(query2,self.listo)
self.current_sales1=self.cursor.fetchall()[0][0]
self.show_plot()
【问题讨论】:
标签: python mysql mysql-connector