I read many articles on Stack Overflow regarding how SQL injection can be prevented by using prepared statements
But is there any way to do SQL injection even on prepar
This query : String query = "SELECT * FROM Users WHERE username=? and password=?";
is safe, because whatever the parameters can be, it will still be executed as a simple select. At most, it will end browsing a whole table.
But prepared statement is just a tool and (bad) programmers may still misuse it.
Let's look at the following query
String query = "SELECT id, " + paramName + " FROM Users WHERE username=? and password=?";
where paramName
would be a parameter name. It is only as safe as paramName
is, because you use directly a variable to build the string that will be parsed by the database engine. Here PreparedStatement
cannot help because JDBC does not allow to parameterize a column name.
So the rule here will be :
paramName
cannot be anything other than what you expect because that control is the only prevention against SQL injection