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

如何使用Python从字典生成SQL更新操作所需的字符串

实现方案

你可以通过列表暂存每一个字段更新表达式,再拼接得到完整SQL,同时需要修正原代码的几处问题:

  1. 原sqlquote用双引号包裹值,不符合SQLite字符串单引号的语法要求
  2. 需要跳过product_id字段,避免将主键放到SET更新范围中
  3. WHERE条件里的product_id值需要从字典取出后转义,不能直接写在字符串里

完整实现代码

def sqlquote(value):
    """简易SQL转义函数
    除了NULL以外的所有值都会用单引号包裹作为SQL字符串返回,内嵌的单引号会自动转义
    """
    if value is None:
         return 'NULL'
    return "'{}'".format(str(value).replace("'", "''"))

# 示例字典
article_dict = {
    "product_name": "无线耳机",
    "price": 299,
    "stock": 320,
    "product_id": 10086
}

part1 = "UPDATE products_list SET"

# 拼接part2
update_expr_list = []
for key, value in article_dict.items():
    if key != "product_id":
        update_expr_list.append(f"{key} = {sqlquote(value)}")
part2 = ", ".join(update_expr_list)

# 拼接part3
part3 = f"WHERE product_id = {sqlquote(article_dict['product_id'])}"

# 得到完整SQL
full_update_sql = f"{part1} {part2} {part3}"
print(full_update_sql)

运行后输出的SQL示例:

UPDATE products_list SET product_name = '无线耳机', price = '299', stock = '320' WHERE product_id = '10086'

更安全的参数化查询方案

如果有SQL注入风险,更推荐用SQLite原生参数化查询,不需要手动处理转义:

import sqlite3

# 生成占位符
update_fields = [k for k in article_dict if k != "product_id"]
placeholder_str = ", ".join([f"{k} = ?" for k in update_fields])
query_params = [article_dict[k] for k in update_fields] + [article_dict["product_id"]]

# 构造SQL
sql = f"UPDATE products_list SET {placeholder_str} WHERE product_id = ?"

# 执行查询
conn = sqlite3.connect("你的数据库路径.db")
cursor = conn.cursor()
cursor.execute(sql, query_params)
conn.commit()

内容的提问来源于stack exchange,提问作者Cristian Avendaño

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 10:36:05