参数化查询Postgres用于sql注入缓解

时间:2015-09-16 08:39:58

标签: python postgresql sql-injection psycopg2 python-db-api

stmt = "SELECT filecontent FROM filecontent WHERE filecontent_id = %d AND filecontent LIKE '%% %s %%'"%(int(result_file_pri[0]),str(myjson['recordType']))
curs.execute(stmt)

尝试将上面的postgres查询转换为参数化查询,以便进行sql注入。我在互联网上找到的解决方案是在执行语句中包含stmt并从引号中取%s,即

curs.execute("SELECT filecontent FROM filecontent WHERE filecontent_id = %s AND filecontent LIKE %% %s %%",(int(result_file_pri[0]),str(myjson['recordType'])))

以上对我来说不适用于%%%s %%,我该如何解决问题呢?

1 个答案:

答案 0 :(得分:2)

它应该是包含百分比字符的参数:

curs.execute("SELECT filecontent FROM filecontent WHERE filecontent_id = %s AND filecontent LIKE %s",
             (int(result_file_pri[0]), str("%" + myjson['recordType'] + "%")))
                                            ^----------------------------^
                                                    so the wildcard is the
                                                     part of the parameter