← Back to Chapters

SQL Injection & Prevention

?️ SQL Injection & Prevention

? Quick Overview

SQL Injection is a critical security vulnerability where attackers manipulate SQL queries by injecting malicious input. In Advanced Java applications using JDBC, improper query handling can expose databases to data theft, corruption, or deletion.

? Key Concepts

  • Unvalidated user input can alter SQL queries
  • Dynamic SQL using string concatenation is dangerous
  • PreparedStatement prevents query manipulation
  • Input validation adds an extra security layer

? Syntax / Theory

SQL Injection occurs when user input is directly embedded into SQL statements. Attackers exploit this to bypass authentication or execute unauthorized queries. Using parameterized queries ensures user input is treated as data, not executable SQL.

? Code Example(s)

❌ Vulnerable JDBC Code

? View Code Example
// Insecure SQL using string concatenation
String user = request.getParameter("username");
String pass = request.getParameter("password");
String sql = "SELECT * FROM users WHERE username='" + user + "' AND password='" + pass + "'";
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(sql);

✅ Secure JDBC Code (PreparedStatement)

? View Code Example
// Secure SQL using PreparedStatement to prevent injection
String sql = "SELECT * FROM users WHERE username=? AND password=?";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1, user);
ps.setString(2, pass);
ResultSet rs = ps.executeQuery();

? Live Output / Explanation

? What Happens?

In the vulnerable version, an attacker can input:

' OR '1'='1

This bypasses authentication. In the secure version, the database treats input strictly as data, blocking malicious execution.

? Interactive Simulator

Type in the inputs below to see how the SQL query is built in real-time.

Generated SQL Query:
 
Query Status: Normal

✅ Tips & Best Practices

  • Always use PreparedStatement instead of Statement
  • Validate and sanitize all user inputs
  • Use least-privilege database accounts
  • Enable database error logging, not error display

? Try It Yourself

  • Create a login form using JDBC and PreparedStatement
  • Test input with special characters like ' and --
  • Compare results between Statement and PreparedStatement