如何将 sql 模板化为 python 并处理 sql 组合问题?

How to template sql with python and deal with sql composition problem?

我需要格式化一个 SQL 查询,它看起来像这样:

s += " t{}.{} = '{}' and".format(t_c, filter_c, filter_value)

但是当 filter_value 类似于 m's 时,它将导致在

psycopg2.errors.SyntaxError: syntax error

如果我使用双引号,它会说没有这样的列

有什么办法可以解决这个问题吗?

由注入漏洞引起。使用 filter_value 的参数并让数据库 API 处理它。

如果 table/schema 名称来自用户输入,也将其列入白名单。 table 名称不能使用参数。

试试这个:

def format_value( string ):
    if '\'' in string:
        k           = string.split('\'')
        string_list = list(map(lambda x: '\'' + x+ '\'', k ))
        return  ''.join(string_list )
    else:
        return string 

然后

filter_value = format_value(filter_value)

在将 filter_value 传递给您的查询之前