如何编码 SQL 选择字符串



我很困惑如何用Python编码。

以下代码从 pgsql 命令行工作。

select * from consultation_tbl where consultation_status in ('S','C','R');

但是在Python中,我不知道如何编码。

chat_str = "'S','C','R'"
cursor.execute(" 
        SELECT * FROM consultation_tbl
        WHERE consultation_status IN ( %s )", [chat_str])

请给我一个建议。

首先,您可以在双引号字符串中使用单引号,这是一个有效的 Python 文字字符串:

chat_str = "'S', 'C', 'R'"

但我会像这样编码:

# 1) This joins the tokens with ', ' separator. Very useful
chat_str = ', '.join(["'S'", "'C'", "'R'",])
# 2) We use the python3 format() method for strings. 
# The '{}' is replaced. See the official docs
query = "SELECT * FROM consultation_tbl
    WHERE consultation_status IN ({})".format(chat_str)
cursor.execute(query)

在这两种情况下,结果字符串都是等效的。

通常,您不希望使用手动卷的刺替换将数据放入查询中 - Python SQL API允许您传入一个元组,它将清理并放入以防止SQL注入。话虽如此,由于 IN 子句中的 parms 列表的长度可以是动态的,因此您可能仍然需要字符串替换来创建模板查询。我通常看到它看起来像这样:

char_list = ['S', 'C', 'R' ]
qry = "SELECT * FROM consultation_tbl WHERE consultation_status IN ( %s )"
qry %= ",".join("%s" for x in range(len(char_list)))
cursor.execute(qry, chars)

最新更新