Intermediate level · Module 5: Using Databases from Applications · Lesson 2 of 3
Parameterised Queries and SQL Injection
Pass values safely to SQL with parameters, and understand how injection attacks work.
In this lesson you will
- Explain SQL injection with an example
- Use parameters for every value from outside the program
Key concepts
SQL injectionplaceholdersparameter bindinginput validation
The lesson
Building SQL by joining strings — "SELECT * FROM households WHERE code = '" + code + "'" — lets an attacker change the query by typing SQL into the input. This is SQL injection, one of the most common and damaging vulnerabilities.
Use placeholders instead: cursor.execute("SELECT * FROM households WHERE code = ?", (code,)) for sqlite3, or %s for psycopg. The driver sends the value separately, so it is always treated as data.
Validate input as well — formats, lengths, allowed values — and give the application's database user only the permissions it needs.
Step by step
- Run a vulnerable query with an injection input on a practice database.
- Rewrite it with a placeholder.
- Repeat the attack and confirm it fails.
- Add input validation.
Practice activity
Make the registration script safe against injection and invalid input.
Expected result: All queries use parameters, and injection attempts and invalid inputs are rejected.
Check your understanding
-
How do parameters prevent SQL injection?
Show answer
The value is sent separately from the SQL, so it is never executed as SQL.
-
What placeholder does Python's sqlite3 use?
Show answer
A question mark (?).
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.