【问题标题】:How to put list values with single quotes as well as double quotes to Postgressql Select Query如何将带有单引号和双引号的列表值放入 Postgresql 选择查询
【发布时间】:2019-09-08 09:47:27
【问题描述】:

我正在对 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.x postgresql


    【解决方案1】:

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

    query = """select category from  "unique_shelf" where "Unique_Shelf_Names" in %s """
    
    cur.execute(query,(list2,))
    

    Tuples adaptation

    【讨论】:

    • 感谢您的回复,但列表格式不是问题
    • @Shubham :请尝试我在回答中提到的选项,如果它不起作用,请告诉我。此外,我发布的链接清楚地提到了如何将值作为元组传递给IN 子句。所以,如果你想使用format,说明你使用了错误的方法。
    • 抱歉 kaushik 我认为格式不是问题。非常感谢你解决了我的问题。
    • @Shubham:不客气。我很高兴能提供帮助。
    猜你喜欢
    • 2019-02-15
    • 2022-01-17
    • 1970-01-01
    • 2020-06-13
    • 1970-01-01
    • 2019-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多