Nov 17

SQL Injection involves taking advantage of a vulnerability in your code that allows an attacker to inject SQL commands into your code.

For example take the following code to check a user login.

String sql = "select * from user where username='" + username +"' and password='" + password + "'";
statement = conn.createStatement();
rs = statement.executeQuery(sql);

That codes makes it possible for a user to include SQL in their username (or password) that would change the function of the above code. For example consider what happens if the following username is used

anyone' or '1'='1

The resulting SQL would be:

select * from user where username='anyone' OR '1'='1' and password=' '

This would allow an attacker to potentially log in without supplying a password.

The easiest way to protect against this type of attack is to always use a PreparedStatement. So our code becomes:

String sql = "select * from user where username=? and password=?;
statement = conn.prepareStatement(sql);
statement.setString(1, username);
statement.setString(2, password);
rs = statement.executeQuery();

By using a PreparedStatement any meta-characters in our parameters now get escaped correctly which protects us from SQL injection.

written by objects \\ tags: , , , ,

One Response to “Use PreparedStatement to protect against SQL Injection”

  1. Trevor Hinson Says:

    Fair point and something that is easily over looked (I’ve messed up in the passed by not spotting this kind of threat though it was with an ASP / MS solution).

    Liking the site.


Leave a Reply

You must be logged in to post a comment.