我正在为我的 web 应用程序编写一个辅助函数,该函数根据从外部 API(不是用户输入的)获取的一些信息来更新数据库。我有以下代码,但它被 Bandit python 包标记为“不安全”。
理想情况下,我可以以硬编码要更新的列的方式编写一个函数,但我认为它也应该可以动态实现。
这是更新表的安全方法(不可能进行 SQL 注入)吗?
import mysql.connector as database
def update_message_by_uid(uid: str, update_dict: dict) -> None:
# Fetches the previous entry from the database using the unique identifier
message_info_dict = get_message_by_uid(uid)
# check that all the keys of the update dict are also in the original dict
assert set(update_dict.keys()) <= set(
message_info_dict.keys()
), "Some of the keys in the dictionary passed are not valid database columns"
# We update the entry for all entries in the dictionary containing the updates
statement = 'UPDATE messages SET {} WHERE uid = %s'.format(", ".join('{}=%s'.format(k) for k in update_dict))
# Concatenates the values of the dict with the unique identifier to pass it to the execution method as one variable
data = list(update_dict.values()) + [uid]
cursor.execute(statement, data) Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
您应该将列名放在反引号中,以防列名是 SQL 保留关键字 或包含空格、标点符号或国际字符。还要确保列名称中的反引号字符替换为两个反引号。
assignments = ", ".join(f"`{k.replace('`', '``')}`=%s" for k in update_dict) statement = f"UPDATE messages SET {assignments} WHERE uid = %s"我更喜欢使用 f 字符串而不是 format()。