【问题标题】:In python, How to do the postgresql 'LIKE %name%' query which mitigate SQL injection?在 python 中,如何执行缓解 SQL 注入的 postgresql 'LIKE %name%' 查询?
【发布时间】:2018-03-14 06:20:27
【问题描述】:

我想执行下面的查询,

select * from table where name LIKE %sachin%;

我是这样创建sql查询的,

sql = "select * from table where %s like '\%%s\%'"

它给了我以下错误,

ValueError: unsupported format character ''' (0x27) at index 42

我想要字符串前后的 '%' 符号。 我怎样才能做到这一点?它还应该减轻 SQL 注入。

【问题讨论】:

标签: python sql postgresql sql-injection


【解决方案1】:

您可以使用 % 作为转义字符。

sql = "select * from table where name like '%%sachin%%'"

对于您的情况,上述查询应该可以工作。

【讨论】:

    【解决方案2】:

    您最好的选择是使用占位符并在 SQL 中生成 LIKE 的右侧值,如下所示。最大的困难是您还期望传递标识符,这意味着您可能需要做一些不同的事情:

    sqltemplate = "select * from table where {} like '%%' || %s || '%%'"
    

    我们在其中填写我们的标识符。请注意,将值列入白名单很重要。

    allowed_columns = ['foo', 'bar', 'bar']
    if colname in allowed_columns:
       sql = sqltemplate.format(colname);
    else:
       raise ValueError('Bad column name!')
    

    然后你可以为 %s 使用一个占位符,它就可以工作了。

    conn.execute(sql, (searchval,));
    

    注意:在 psycopg2 中,您使用 %s%d 作为占位符,使用 %% 表示文字百分比。

    【讨论】:

    • 我试过了 self.cursor.execute("select count() from table where 1 = ?", (1,)) 。出现错误:第 1 行:从 1 = 的表中选择计数()? .不工作。
    • count(*),不是 count()
    • 好的,结果 psycopg 使用 %s 作为占位符。答案已更新。
    • 还是不行。这工作正常: sql = "SELECT name FROM table where username like '%sachin%'" ,但这不起作用: sql = "SELECT name FROM table where username like '%%' || %s ||'% %'"; self.cursor.execute(sql, ("sachin", ));没有给出任何错误,但没有获取所需的结果。
    猜你喜欢
    • 2012-11-19
    • 1970-01-01
    • 2020-04-23
    • 1970-01-01
    • 2021-10-21
    • 2017-07-24
    • 2020-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多