Showing posts with label JDBC. Show all posts
Showing posts with label JDBC. Show all posts

Friday, March 11, 2011

Prevent SQL Injection Attacks in Java

To prevent hackers from exploiting your Java website:

NEVER do this (manually concatenate SQL):

String sql = "select 1 from user where userId='" + userId + "' and password='" + password + "'";

Instead do this (use prepared statements):

String sql = "select 1 from user where userId = ? and password = ?";
PreparedStatement prepStmt = con.prepareStatement(sql);
prepStmt.setString(1, userId);
prepStmt.setString(2, password);

When you use prepared statements it passes the parameters directly to the database independent of the SQL statement so that the hacker never has a chance to alter them.