Search code examples
pythonpostgresqlsql-injectionpsycopg2python-db-api

parameterized query Postgres for sql injection mitigation


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

Trying to conevert above postgres query to parameterized query to itigate sql injection. The solution I found on internet is to include stmt in execute statement and take %s out of quotes i.e

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

The above doesn't work for %% %s %% for me, how do I rectify the problem?


Solution

  • It should be the parameter that holds the percent character:

    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