What is SQL injection?
SQL injection happens when you inject some content into a SQL query string, and the result modifies the syntax of your query in ways you didn't intend.
Injected SQL commands can alter SQL statement and compromise the security of an application.
SQL Injection Based on 1=1 is Always True
SQL Injection Based on ""="" is Always True
This code is vulnerable to SQL Injection because it uses dynamic queries to concatenate malicious data to the query itself.
This code is also vulnerable to SQL Injection. Even though it uses the PreparedStatement class it is still creating the query dynamically via string concatenation.
Fix SQL injection using PreparedStatement
A PreparedStatement represents a precompiled SQL statement that can be executed multiple times without having to recompile for every execution.
This code is not vulnerable to SQL Injection because it correctly uses parameterized queries. By utilizing Java's PreparedStatement class, bind variables (i.e. the question marks) and the corresponding setString methods, SQL Injection can be easily prevented.
Advantage of PreparedStatement?
Improves performance: The performance of the application will be faster if you use PreparedStatement interface because query is compiled only once.