Skip to main content

How do you protect against SQL injections?

Protection against SQL injections comes down to never letting a user directly influence the SQL statement.

The main techniques

Here are the main techniques:

  1. Use parameterized queries (prepared statements). Instead of concatenating strings with user input, pass the data as parameters. Example (Python + PostgreSQL):
python
cursor.execute("SELECT * FROM users WHERE login = %s", (user_input,))

Here the input isn't inserted into the query text, it's passed safely. 2. Never build queries through string concatenation. Never do this:

python
"SELECT * FROM users WHERE login = '" + user_input + "'"
  1. Validate and constrain user input. Allow only valid characters, lengths, and formats (e.g. only letters and digits).
  2. Use an ORM or framework. For example, SQLAlchemy, Django ORM, Hibernate, they automatically escape parameters.
  3. Limit database user privileges. The application should connect as a user that has no rights to drop tables or change the schema.
  4. Log and monitor suspicious queries. To catch attempted attacks quickly.

Summary: protection against SQL injections comes down to parameters instead of strings, input validation, and minimal privileges for the database account.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.