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: , , , ,

Oct 27

The executeUpdate() method of Statement class returns the number of rows affected


   in rows = staement.executeUpdate(sql);

written by objects \\ tags: ,