Python 3.x psycopg2编程错误-带连字符的参数
Python 3.x psycopg2编程错误-带连字符的参数,python-3.x,postgresql,psycopg2,Python 3.x,Postgresql,Psycopg2,self.id类似于N-1f27va5(始终有连字符)。假设光标和连接已经建立。我听到这样一个错误:psycopg2.ProgrammingError:syntax error位于或接近“f27va5”。psycopg2读取连字符或其他东西有问题吗?在这种情况下,解决方案是什么?您的陈述会是这样的 sql = 'select "productID" from "Barneys_Output" where "designerID" = %s' %self.id db = self.cursor.e
self.id
类似于N-1f27va5
(始终有连字符)。假设光标和连接已经建立。我听到这样一个错误:psycopg2.ProgrammingError:syntax error位于或接近“f27va5”。psycopg2读取连字符或其他东西有问题吗?在这种情况下,解决方案是什么?您的陈述会是这样的
sql = 'select "productID" from "Barneys_Output" where "designerID" = %s' %self.id
db = self.cursor.execute(sql)
这不是有效的SQL语法。你不应该自己格式化字符串。最好是PyGreSQL为您这样做:
select "productID" from "Barneys_Output" where "designerID" = N-1f27va
这将正确转义字符串。这应该会产生类似的结果
sql = 'select "productID" from "Barneys_Output" where "designerID" = %s'
db = self.cursor.execute(sql, (self.id, ))
虽然这个示例非常简单,但您不应该自己屏蔽参数,因为PyGreSQL正确地处理特殊字符或其他数据类型,如
date
或datetime
。我不确定,但这也可以降低SQL注入的风险。@Tahtakafa
select "productID" from "Barneys_Output" where "designerID" = 'N-1f27va'