The Problem
Most developers think their database is safe. It's not. SQL injection attacks can destroy everything.
What is SQL Injection?
If you write code like this:
query = f"SELECT * FROM users WHERE username = '{username}'"
An attacker types: admin' OR '1'='1
Your query becomes:
SELECT * FROM users WHERE username = 'admin' OR '1'='1'
All users exposed. Game over.
The Solution: Parameterized Queries
Never use f-strings for queries. Use parameters:
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
user = db.session.execute(
db.select(User).where(User.username == username)
).scalar()
SQLAlchemy automatically escapes dangerous characters.
Why It Works
- Database treats input as DATA, not CODE
- Even if attacker types
admin' OR '1'='1', it's treated as literal string - Safe from injection
Common Mistakes
- Using f-strings for queries ❌
- Not validating input ❌
- Trusting user data ❌
Conclusion
Always use parameterized queries. Never build queries with string formatting.
Top comments (0)