【发布时间】:2021-12-20 01:08:51
【问题描述】:
我有一个包含来自 MySQL DB 的选定字段值的组合框。如何使字段ID而不是ComboBox中的值传递给数据库?
这是对数据库添加记录的请求:
def new_module(self):
def new_module_add(Event):
dt = str(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
with self.con.cursor() as cur:
cur.execute("INSERT INTO modules (version, date, description, common_id) VALUES ('"+str(self.module_entry0.get())+"', '"+dt+"', '"+str(self.module_description.get("1.0", END))+"', '"+module_common.get()+"')")
self.con.commit()
print(self.module_common.get())
这是 ComboBox 本身:
with self.con.cursor() as cur:
cur.execute("SELECT * FROM common_data")
c = cur.fetchall()
self.module_common = ttk.Combobox(master=self.new_module,
text="Engine",
values = [(c[i][1]) for i in range(len(c))], state='readonly')
self.module_common.grid(row=7, column=0)
我需要值c[i][0],即ID。是否可以以某种方式添加此变量以将其传输到数据库?
【问题讨论】:
-
请edit您的问题并修正代码的缩进。
-
combobox应该为您提供所选元素的索引,您应该使用它从c获取 ID,例如ID = c[selected][0] -
首选(出于安全原因):
execute("INSERT ... VALUES (?, ?, ?)", (value1, value2, value3)) -
你应该学会在没有
range(len())的情况下使用for-loop——它提供了更易读的代码,比如values = [row[1] for row in c]而不是values = [(c[i][1]) for i in range(len(c))]