psycopg2 and SQL injection security

You can use psycopg2.sql to compose dynamic queries. Unlike AsIs it will protect you from SQL injection.


AsIs is unsafe, unless you really know what you are doing. You can use it for unit testing for example.

Passing parameters is not that unsafe, as long as you do not pre-format your sql query. Never do:

sql_query = 'SELECT * FROM {}'.format(user_input)
cur.execute(sql_query)

Since user_input could be ';DROP DATABASE;' for instance.

Instead, do:

sql_query = 'SELECT * FROM %s'
cur.execute(sql_query, (user_input,))

pyscopg2 will sanitize your query. Also, you can pre-sanitize the parameters in your code with your own logic, if you really do not trust your user's input.

Per psycopg2's documentation:

Warning Never, never, NEVER use Python string concatenation (+) or string parameters interpolation (%) to pass variables to a SQL query string. Not even at gunpoint.

Also, I would never, ever, let my users tell me which table I should query. Your app's logic (or routes) should tell you that.

Regarding AsIs(), per psycopg2's documentation :

Asis()... for objects whose string representation is already valid as SQL representation.

So, don't use it with user's input.


If you need to store your query in a variable you can use the SQL method (documentation) :

from psycopg2 import sql


query = sql.SQL("SELECT * FROM Client where id={clientId}").format(clientId=sql.Literal(clientId)