You prepareStatement is still vulnerable if you do like this
By Admin
•
November 2, 2025
String sql = "SELECT *FROM users WHERE username = '" + userInput + "'";
PreparedStatement pstmt = connection.prepareStatement(sql);
is this code vulnerable? I am using prepared statement.
The Vulnerability
You are incorrectly building the SQL query string before passing it to connection.prepareStatement().
- Vulnerable Code:Java
String sql = "SELECT * FROM users WHERE username = '" + userInput + "'"; // ❌ Flaw here PreparedStatement pstmt = connection.prepareStatement(sql); - The Flaw: By concatenating userInput directly into the sql string, you are treating user input as part of the SQL command's structure. If an attacker enters a malicious string like ' OR '1'='1, the resulting query sent to the database is:SQLThis bypasses authentication because the OR '1'='1' clause evaluates to true for every row.
SELECT * FROM users WHERE username = '' OR '1'='1'
✅ The Correct Fix
To use PreparedStatement securely, you must use a placeholder (?) in the query string and set the user input separately using a set... method.
- Secure Code:Java
String sql = "SELECT * FROM users WHERE username = ?"; // ✅ Use placeholder PreparedStatement pstmt = connection.prepareStatement(sql); pstmt.setString(1, userInput); // ✅ Set input separately // Now execute the query (e.g., pstmt.executeQuery();)
By using the placeholder, the database driver handles the userInput strictly as data, automatically escaping any malicious characters and eliminating the injection risk.
