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.
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.
// 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 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();
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.
Type in the inputs below to see how the SQL query is built in real-time.
PreparedStatement instead of Statement' and --