为什么带有 SQL 查询参数的 psycopg2cursor.execute() 会导致语法错误?
当在Python中的psycopg2中指定execute()的参数时,如下所示:
cursor.execute('SELECT * FROM %s', ("my_table", ))
我收到此错误:
psycopg2.ProgrammingError: syntax error at or near "'my_table'"
LINE 1: SELECT * FROM 'my_table'
我做错了什么?看起来 psycopg2 正在向查询添加单引号,而这些单引号导致了语法错误。
如果我不使用参数,它会正常工作:
cursor.execute('SELECT * FROM my_table')
When specifying a parameter to execute() in psycopg2 in Python, like this:
cursor.execute('SELECT * FROM %s', ("my_table", ))
I'm getting this error:
psycopg2.ProgrammingError: syntax error at or near "'my_table'"
LINE 1: SELECT * FROM 'my_table'
What am I doing wrong? It looks like psycopg2 is adding single quotes to the query, and those single quotes are causing the syntax error.
If I don't use a parameter, it works correctly:
cursor.execute('SELECT * FROM my_table')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我相信像这样的参数化语句应该与值一起使用,而不是与表名(或 SQL 关键字等)一起使用。所以你基本上不走运。
不过,不用担心,因为这种机制是为了防止 SQL 注入,而且您通常在编写代码时就知道要访问哪个表,因此有人注入恶意代码的可能性很小。只需继续将表格写入字符串即可。
如果出于某种(可能是反常的)原因,您将表名保持参数化,如下所示:
例如:
#1
:让此时将第三个 %s 替换为另一个 '%s',以允许 psycopg2 稍后进行处理#2
:这是 psycopg2 将正确引用并放置的字符串,而不是原始字符串中的第三个“%s”I believe that parametrized statements like this are meant to be used with values and not table names (or SQL keywords, etc.). So you're basically out of luck with this.
However, do not worry, as this mechanism is meant to prevent SQL injection, and you normally know what table you want to access at code-writing time, so there is little chance somebody may inject malicious code. Just go ahead and write the table in the string.
If, for some (possibly perverse) reason you keep the table name parametric like that:
For example:
#1
: Let the third %s be replaced with another '%s' at this time, to allow later processing by psycopg2#2
: This is the string that will be properly quoted by psycopg2 and placed instead of that third '%s' in the original stringPsycopg2 中的功能通过 SQL 字符串组合。这种方法提供了一种“以方便且安全的方式动态生成 SQL”的方法。
在原始答案的用例中:
使用 SQL 字符串组合是比 Irfy 答案中讨论的通过
%
进行字符串参数插值更安全的方法。正如 psycopg2 文档中所述:There is functionality within Psycopg2 that supports this use case via SQL String Composition. This approach provides a way to "generate SQL dynamically, in a convenient and safe way."
In the use case in the original answer:
Using SQL String Composition is a much safer approach than string parameter interpolation via
%
discussed in Irfy's answer. As noted in the psycopg2 documentation: