我正在对postgresql数据库执行选择查询,在获取这些结果后,我将这些结果附加到列表中,然后将该列表作为另一个postgresql选择查询的输入。
但是由于这些值转换为列表,它将带有撇号(特殊字符)的值cat的
转换为双引号"cat的"
。在执行第二次选择查询时,没有获取带有双引号的值,因为带有双引号的值在数据库中不存在,它没有双引号cat的
。
并且它给我错误的值不存在。
我试过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”不存在
但在数据库中leopard's存在的地方。
我希望query_list
中的所有值都是双引号,这样就不会出现这个错误。
不要使用format
来构造查询。只需使用%s
并将元组传递给执行
query = """select category from "unique_shelf" where "Unique_Shelf_Names" in %s """
cur.execute(query,(list2,))
元组适配