What is SQL injection and how can it be prevented?

Beginner

Answer

SQL injection occurs when user input is directly concatenated into SQL queries, allowing attackers to manipulate the database.

Example of vulnerable code:

# VULNERABLE
query = f"SELECT * FROM users WHERE username = '{username}'"

Attack example: username = "admin'; DROP TABLE users; --"

Prevention methods:

  1. Parameterized queries/Prepared statements (most effective)
  2. Stored procedures (when properly implemented)
  3. Input validation (whitelist approach)
  4. Least privilege principle for database accounts
  5. Web Application Firewalls (additional layer)

Secure example:

# SECURE - Using parameterized query
cursor.execute("SELECT * FROM users WHERE username = %s", (username,))