Java Why PreparedStament not Statement

This is a story of why is it that me, a programmer uses PreparedStatement instead of Statement when doing SQL queries in my projects.

After what seemed to be a so called secure connection to my database and login system, written by a so called 3rd party, I found out that I can indelibly hack into the system when I use SQL injection. Huh? What’s this? You see, all I need to know at times is your username and I can find ways to login.

But that’s just logging in, what about dropping your table. Here’s an example of why

public List processUser(String username, String password)
   throws SQLException
   String query = "SELECT * FROM userTbl WHERE id = '" + username + 
"' and pass= '" + password + "'";
   ResultSet rs = this.connection.executeQuery(query);
   // ... process results ...

The above seems very innocently innocent. Now imagining a login page. The user enters something weird. For example in password field he/she does this.

abc’ or a = ‘a

Now how would it look like.

String query = "SELECT * FROM userTbl WHERE id = '" + username +
"' and pass= '" + abc' or a = 'a + "'";

Now can you finally see the dangerousness of using Statement. The difference in using PreparedStatement I can now control what the user enters. To see some of my previous SQL queries using PreparedStatement refer this previous post about SQL.

So always be aware of the security of your codes. Hope this bring some enlightenment to the programmers out there.

Leave a Reply