You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python+MySQL开发中如何将ComboBox选中项对应的ID传递到数据库

解决方案

你可以通过建立「下拉框显示文本-数据库ID」的映射字典实现需求,具体修改如下:

1. 新增映射字典存储对应关系

修改ComboBox初始化部分的代码,在查询完common_data后新增映射存储逻辑:

with self.con.cursor() as cur:
    cur.execute("SELECT * FROM common_data")
    c = cur.fetchall()

# 新增映射字典:key为下拉框展示的文本,value为对应数据库的ID值
self.common_id_map = {item[1]: item[0] for item in c}

self.module_common = ttk.Combobox(
    master=self.new_module,
    text="Engine",
    values = list(self.common_id_map.keys()), 
    state='readonly'
)
self.module_common.grid(row=7, column=0)

2. 提交数据时通过映射取ID

修改插入数据的代码,同时建议将原有的字符串拼接SQL改为参数化查询,避免SQL注入风险:

def new_module(self):
    def new_module_add(Event):
        dt = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        # 先判断是否有选中项,避免KeyError
        selected_text = self.module_common.get()
        if selected_text not in self.common_id_map:
            # 可自行添加未选中的提示逻辑
            return
        selected_common_id = self.common_id_map[selected_text]
        with self.con.cursor() as cur:
            # 使用参数化查询,不要直接拼接SQL字符串
            cur.execute(
                "INSERT INTO modules (version, date, description, common_id) VALUES (%s, %s, %s, %s)",
                (self.module_entry0.get(), dt, self.module_description.get("1.0", END), selected_common_id)
            )
        self.con.commit()
        print(selected_common_id)

注:如果你的common_data表中存在重复的显示文本(即c[i][1]重复),可以给重复文本加后缀区分,或者给Combobox绑定<<ComboboxSelected>>事件,选中时实时存储对应ID即可。

内容的提问来源于stack exchange,提问作者Никита Климов

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 04:54:03