首页 > 解决方案 > 如何将带有单引号和双引号的列表值放入 Postgressql Select Query

问题描述

我正在对 postgresql 数据库执行选择查询,在获取这些结果后,我将这些结果附加到列表中,然后将该列表作为另一个 postgresql 选择查询的输入。

但是由于将这些值转换为列表,它会将带有撇号(特殊字符)的值转换cat's为双引号"cat's"。在执行第二个选择查询时,未获取带有双引号的值,因为带有双引号的值不存在于数据库中,它没有双引号cat's
它给了我价值不存在的错误。

我尝试过 JSON 转储方法,但它不起作用,因为我无法将 JSON 列表转换为元组并将其作为 postgresql 选择查询的输入

select_query = """select "Unique_Shelf_Names" from "unique_shelf" where category = 'Accessory'"""
cur.execute(select_query)
count = cur.fetchall()

query_list = []
for co in count:
    for c in co:
        query_list.append(c)

输出query_list

query_list = ['parrot', 'dog', "leopard's", 'cat', "zebra's"]

现在这querylist被转换为元组并作为另一个选择查询的输入。

list2 = tuple(query_list)

query = """select category from  "unique_shelf" where "Unique_Shelf_Names" in {} """.format(list2)

cur.execute(query)

这是它给我错误的地方,"leopard's" doesn't exist但在数据库豹的存在。

我希望 中的所有值query_list都是双引号,这样就不会出现此错误。

标签: python-3.xpostgresql

解决方案


不要format用于构造查询。只需使用%s并将元组传递给execute

query = """select category from  "unique_shelf" where "Unique_Shelf_Names" in %s """

cur.execute(query,(list2,))

元组适应


推荐阅读