问题描述
我正在尝试查看数据库中是否已有项目。但是我不知道如何选择其中带有撇号(')的名称。
我尝试使用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()
请注意,值必须作为元组传递。