具有SQL查询参数的psycopg2 cursor.execute()导致语法错误

编程入门 行业动态 更新时间:2024-10-27 18:30:45
本文介绍了具有SQL查询参数的psycopg2 cursor.execute()导致语法错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在Python的psycopg2中指定要执行的参数时,如下所示:

When specifying a parameter to execute() in psycopg2 in Python, like this:

cursor.execute('SELECT * FROM %s', ("my_table", ))

我收到此错误:

psycopg2.ProgrammingError: syntax error at or near "'my_table'" LINE 1: SELECT * FROM 'my_table'

我在做什么错?看起来psycopg2在查询中添加了单引号,而这些单引号导致了语法错误。

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')

推荐答案

我相信这样的参数化语句应与 values 一起使用,而不是与表名一起使用(或SQL关键字等)。因此,您基本上对此感到不走运。

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.

但是,请不要担心,因为该机制是为了防止SQL注入,而且您通常知道要使用哪个表可以在编写代码时访问,因此几乎没有机会注入恶意代码。

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:

  • 如果表名来自您的程序(例如字典或类属性),请执行通常的字符串替换。
  • 如果表名来自外部世界(请考虑用户输入):要么不这样做,要么完全信任用户并应用以前的方法1。
  • 例如:

    cursor.execute( 'SELECT * FROM %s where %s = %s' % ("my_table", "colum_name", "%s"), #1 ("'some;perverse'string;--drop table foobar")) #2

    #1 :此时将用另一个'%s'替换第三个%s,以允许psycopg2 #2 进行后续处理:这是正确的字符串由psycopg2引用并放置在原始strin中而不是第三个'%s' g

    #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 string

    更多推荐

    具有SQL查询参数的psycopg2 cursor.execute()导致语法错误

    本文发布于:2023-10-19 20:32:46,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1508694.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:参数   语法错误   SQL   execute   cursor

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!