使用postgres / Python选择撇号

问题描述

我正在尝试查看数据库中是否已有项目。但是我不知道如何选择其中带有撇号(')的名称。

我尝试使用Adapt%s(这根本不起作用)。 :item语法也不起作用。

下面的选择将导致

Exception has occurred: ProgrammingError
(psycopg2.errors.SyntaxError) syntax error at or near "s"
LINE 1: select * from items where name = 'Akunda's Bite'

# CODE
str_sql = text(f"select * from items where name = '{item_name}'")

results = self.conn.execute(str_sql).fetchone()

解决方法

使用DB-API的parameter substitution method:而不是使用(f-)字符串格式:

str_sql = text("select * from items where name = %s;")
results = self.conn.execute(str_sql,(item_name,)).fetchone()

请注意,值必须作为元组传递。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...