psycopg2 ProgrammingError - 带连字符的参数
psycopg2 ProgrammingError - Parameters with Hyphens
sql = 'select "productID" from "Barneys_Output" where "designerID" = %s' %self.id
db = self.cursor.execute(sql)
self.id
类似于 N-1f27va5
(总是有一个连字符)。假设游标和连接已经建立。我收到此错误消息 psycopg2.ProgrammingError: syntax error at or near "f27va5"
。 psycopg2 读取连字符有问题吗?在这种情况下,解决方案是什么?
你的陈述看起来像
select "productID" from "Barneys_Output" where "designerID" = N-1f27va
这是无效的 SQL 语法。你不应该自己格式化字符串。最好 PyGreSQL 为你做这些:
sql = 'select "productID" from "Barneys_Output" where "designerID" = %s'
db = self.cursor.execute(sql, (self.id, ))
这将正确转义字符串。这应该产生类似
的东西
select "productID" from "Barneys_Output" where "designerID" = 'N-1f27va'
虽然这个例子非常简单,但您不应该自己屏蔽参数,因为 PyGreSQL 可以正确处理特殊字符或其他数据类型,如 date
或 datetime
。
sql = 'select "productID" from "Barneys_Output" where "designerID" = %s' %self.id
db = self.cursor.execute(sql)
self.id
类似于 N-1f27va5
(总是有一个连字符)。假设游标和连接已经建立。我收到此错误消息 psycopg2.ProgrammingError: syntax error at or near "f27va5"
。 psycopg2 读取连字符有问题吗?在这种情况下,解决方案是什么?
你的陈述看起来像
select "productID" from "Barneys_Output" where "designerID" = N-1f27va
这是无效的 SQL 语法。你不应该自己格式化字符串。最好 PyGreSQL 为你做这些:
sql = 'select "productID" from "Barneys_Output" where "designerID" = %s'
db = self.cursor.execute(sql, (self.id, ))
这将正确转义字符串。这应该产生类似
的东西select "productID" from "Barneys_Output" where "designerID" = 'N-1f27va'
虽然这个例子非常简单,但您不应该自己屏蔽参数,因为 PyGreSQL 可以正确处理特殊字符或其他数据类型,如 date
或 datetime
。