Security

SQL Injection in Java: Fix with PreparedStatement

SQL injection in Java occurs when user input is concatenated into SQL strings. Java's JDBC provides PreparedStatement as the standard fix — but developers frequently use Statement with string concatenation instead.


❌ Vulnerable JDBC Code

public User getUser(String username) throws SQLException {
    Statement stmt = connection.createStatement();
    ResultSet rs = stmt.executeQuery(
        "SELECT * FROM users WHERE username = '" + username + "'"
    );
    return rs.next() ? mapUser(rs) : null;
}

✅ Safe with PreparedStatement

public User getUser(String username) throws SQLException {
    String sql = "SELECT * FROM users WHERE username = ?";
    PreparedStatement stmt = connection.prepareStatement(sql);
    stmt.setString(1, username);
    ResultSet rs = stmt.executeQuery();
    return rs.next() ? mapUser(rs) : null;
}
💡

Pro tip: JPA and Hibernate build parameterized queries by default. Avoid JPQL string concatenation the same way you would avoid raw SQL string concatenation.

Paste this code into LearnCodeGuide

Detect Java vulnerabilities and bugs automatically with AI-powered analysis.

Analyze Java Code →

Related Guides

Java XssJava Command InjectionPython Sql Injection