Does the preparedStatement avoid SQL injection?

Using string concatenation for constructing your query from arbitrary input will not make PreparedStatement safe. Take a look at this example:

preparedStatement = "SELECT * FROM users WHERE name = '" + userName + "';";

If somebody puts

' or '1'='1

as userName, your PreparedStatement will be vulnerable to SQL injection, since that query will be executed on database as

SELECT * FROM users WHERE name = '' OR '1'='1';

So, if you use

preparedStatement = "SELECT * FROM users WHERE name = ?";
preparedStatement.setString(1, userName);

you will be safe.

Some of this code taken from this Wikipedia article.


Well simply using PreparedStatement doesn't make you safe. You have to use parameters in your SQL query which is possible with PreparedStatement. Look here for more information.


The prepared statement, if used properly, does protect against SQL injection. But please post a code example to your question, so we can see if you are using it properly.