Prevent SQL injection attacks in a Java program

You need to use PreparedStatement. e.g.

String insert = "INSERT INTO customer(name,address,email) VALUES(?, ?, ?);";
PreparedStatement ps = connection.prepareStatement(insert);
ps.setString(1, name);
ps.setString(2, addre);
ps.setString(3, email);

ResultSet rs = ps.executeQuery();

This will prevent injection attacks.

The way the hacker puts it in there is if the String you are inserting has come from input somewhere - e.g. an input field on a web page, or an input field on a form in an application or similar.


I want to know how this kind piece of code("DROP TABLE customer;") can be added to my insert statement by a hacker

For example:

name = "'); DROP TABLE customer; --"

would yield this value into insert:

INSERT INTO customer(name,address,email)     VALUES(''); DROP TABLE customer; --"','"+addre+"','"+email+"');

I specially want to know how can I prevent this

Use prepared statements and SQL arguments (example "stolen" from Matt Fellows):

String insert = "INSERT INTO customer(name,address,email) VALUES(?, ?, ?);";
PreparedStament ps = connection.prepareStatment(insert);

Also parse the values you have on such variables and make sure they don't contain any non-allowed characters (such as ";" in a name).


An attacker just has to enter something like '[email protected]"); DROP TABLE customer; into the field for email and you are done.

You can prevent this by using the proper escaping for JDBC Statements.


You can check THIS article for info on that! :)

I recommend Parameterized Queries:

String selectStatement = "SELECT * FROM User WHERE userId = ? ";
PreparedStatement prepStmt = con.prepareStatement(selectStatement);
prepStmt.setString(1, userId);
ResultSet rs = prepStmt.executeQuery();