python-3.x - 如何将带有单引号和双引号的列表值放入 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
都是双引号,这样就不会出现此错误。
解决方案
不要format
用于构造查询。只需使用%s
并将元组传递给execute
query = """select category from "unique_shelf" where "Unique_Shelf_Names" in %s """
cur.execute(query,(list2,))
推荐阅读
- python - 我可以将 Tensorflow keras predict 方法保存为可执行文件吗?
- php - Laravel 使用控制器“向后”删除外键
- xslt-2.0 - 如何根据条件访问上一个和下一个项目
- haskell - 向命令式语言解析器添加 IO 功能
- javascript - Vue Mixin 属性为空白/空/无反应
- angular - Angular cli build prod:TypeError:无法读取未定义问题的属性“种类”
- amazon-web-services - 如何在 EC2 实例的启动和停止后修复 AWS Cloud Formation 漂移?
- angular - 我应该如何在 Ionic 4 中构建我的组件?
- python - 如何将多行 Reddit 数据(使用 praw)写入 csv/txt 文件?
- docker - 如何在安装了 Jupyter Notebook 和 Keras 的情况下构建自定义 docker 映像?