SQL Injection Defense
Prevent injection attacks.
SQL Injection Defense is a free Cyber Security Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Cyber Security Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What Is SQL Injection
SQL injection (SQLi) happens when untrusted user input is concatenated directly into a SQL query. The attacker smuggles SQL syntax into a field that the application expects to be plain data, changing the meaning of the query.
It remains one of the most damaging web vulnerabilities because it can leak entire databases, bypass logins, or destroy data.
A Vulnerable Query
The classic mistake is string concatenation. If the input is tom the query is fine, but a crafted input rewrites the logic.
- The single quote closes the string early.
- Everything after becomes executable SQL.
query = "SELECT * FROM users WHERE name = '" + userInput + "'";
// userInput = tom' OR '1'='1
// becomes: SELECT * FROM users WHERE name = 'tom' OR '1'='1'Authentication Bypass
Login forms are a prime target. By injecting an always-true condition and commenting out the rest, an attacker logs in without a password.
The -- sequence comments out the remaining clause so the password check is ignored.
-- attacker enters in the username field:
admin' --
-- resulting query:
SELECT * FROM users WHERE user = 'admin' --' AND pass = '...'Parameterized Queries
The primary defense is parameterized queries (prepared statements). The SQL structure is sent separately from the data, so input is always treated as a value, never as code.
The database driver binds ? placeholders to the supplied values safely.
-- Python (sqlite3 / psycopg)
cur.execute(
'SELECT * FROM users WHERE name = ? AND pass = ?',
(username, password)
)Prepared Statements in Java
Every major language offers parameterization. In Java, use PreparedStatement instead of building strings with Statement.
Bound parameters cannot break out of their slot, so injection is structurally impossible here.
PreparedStatement ps = conn.prepareStatement(
"SELECT * FROM users WHERE name = ?");
ps.setString(1, userInput);
ResultSet rs = ps.executeQuery();Stored Procedures
Stored procedures can help when they use parameterized inputs internally. But beware: a stored procedure that builds dynamic SQL by concatenation is just as vulnerable.
- Safe: parameters passed to the proc.
- Unsafe:
EXEC()of concatenated strings inside the proc.
Input Validation and Allowlisting
Validation is a useful second layer. Use allowlists (accept only known-good patterns) rather than blocklists (try to ban bad characters).
For example, a numeric ID field should reject anything that is not digits before it ever reaches the query.
if not user_id.isdigit():
raise ValueError('invalid id')
# only then use the valueEscaping Is a Last Resort
Manually escaping quotes is fragile and error-prone. Different databases have different escape rules, and edge cases (encoding tricks, second-order injection) slip through.
Prefer parameterized queries. Use escaping only when an ORM or driver cannot parameterize a specific identifier.
Least Privilege for DB Accounts
Limit the damage of any successful injection by applying least privilege to the application database user.
- Grant only
SELECT,INSERT,UPDATEon needed tables. - Never use a superuser/
rootaccount for the app. - Deny
DROP,FILE, and admin rights.
GRANT SELECT, INSERT, UPDATE ON appdb.orders TO 'webapp'@'%';
REVOKE DROP, ALTER ON appdb.* FROM 'webapp'@'%';ORMs and Query Builders
Modern ORMs (Hibernate, Sequelize, Django ORM, SQLAlchemy) parameterize by default, which removes most injection risk.
The danger returns when developers drop to raw SQL or use string interpolation in a query builder. Always pass values as bound parameters even in raw mode.
Defense in Depth
No single control is enough. Combine layers:
- Parameterized queries everywhere (primary).
- Input validation / allowlisting.
- Least-privilege DB accounts.
- A web application firewall (WAF) to catch known patterns.
- Error handling that never leaks SQL or stack traces.
Quick Check
Test your understanding of the main defense.
Recap
You learned how SQL injection works and how to stop it:
- SQLi arises from concatenating untrusted input into queries.
- Parameterized queries are the primary defense.
- Add allowlist validation, least-privilege DB accounts, and a WAF.
- Avoid manual escaping and dynamic SQL inside stored procedures.
Defense in depth keeps a single mistake from becoming a breach.
Frequently asked questions
Is the “SQL Injection Defense” lesson free?
Yes — the full text of “SQL Injection Defense” is free to read here on the web, and the Cyber Security Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Cyber Security Academy course, upgrade to CoddyKit PRO.
What will I learn in “SQL Injection Defense”?
Prevent injection attacks. You practise Cyber Security Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Cyber Security Academy?
No prior experience is required. Cyber Security Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “SQL Injection Defense” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Cyber Security Academy lesson?
Yes. Every Cyber Security Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- SQL Injection Defense
- Access Control and Encryption
- Auditing and Monitoring
- Backup and Recovery Security