Search code examples
javasql-injection

Are numeric parameters subject to SQL injection attacks?


Consider this statement:

PreparedStatement stmt = connection.prepareStatement("SELECT * FROM t WHERE id=?");
stmt.setInt(1, id);

The above is considered safe from SQL Injection attacks. Is the one below also safe, knowing that id is of type int?

PreparedStatement stmt = connection.prepareStatement("SELECT * FROM t WHERE id=" + id);

If not, what can go wrong?


Solution

  • I can think of two things that might go wrong even if id is an int and can never be anything else:

    1. Someone in the future might change the id type to a String.
    2. Someone might copy-paste your code to another part of the codebase, and then modify the SQL so that it's concatenated with a String, making that part vulnerable.