9

Just last week, I was doing some PHP stuff. I worked a little solution to prevent SQL injections. PHP has been always my man, it has readily 3 solutions for use (maybe more). One is to enable "magic queries" using stripslashes() function. Another one (the recommended) is to use mysql_real_escape_string() function. That simple and my problem is solved. However, things don't seem to be that simple when it comes to JSP. I searched and didn't find any built-in function to strip slashes or do those sort of things (I believe such functionality can be implemented using basic JAVA functions but...).

Please help me protect my database. I heard about PreparedStatement, but really can't get my head around it? (I feel the real meaning of newbieness).

Nadjib Mami
  • 5,736
  • 9
  • 37
  • 49

1 Answers1

24

Just use PreparedStatement instead of Statement.

I.e. use

String sql = "INSERT INTO tbl (col1, col2, col3) VALUES (?, ?, ?)";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, col1);
preparedStatement.setString(2, col2);
preparedStatement.setString(3, col3);
preparedStatement.executeUpdate();

instead of

String sql = "INSERT INTO tbl (col1, col2, col3) VALUES ('" + col1 + "', '" + col2 + "', '" + col3 + "')";
statement = connection.createStatement();
statement.executeUpdate(sql);

The PreparedStatement also offers convenient setter methods for other types, such as setInt(), setDate(), setBinaryStream(), etcetera.

Please note that this issue is unrelated to JSP. It's related to Java in general. Writing raw Java code in a JSP class is also considered a poor practice. Best practice is to create a standalone class which does all the DB interaction tasks on a particular table, which is also called a DAO (Data Access Object) class. You can then import/use this DAO class in a servlet class.

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Wow, here is a comment that spreads a ton of information, your comment was very helpful to me, you made it simple, I thank you and it's solved because of you! – Nadjib Mami Jun 08 '11 at 00:03
  • You're welcome. By the way, it was an answer, not a comment. Those tiny things which you see below questions/answers are comments :) – BalusC Jun 08 '11 at 00:17
  • 1
    +1 for the "Java code in JSP is a bad practice" comment. It seems like such a great idea when you're getting going with JSPs, but oh the pain when you return later to rip out all that non-view related logic. – Marvo Jun 08 '11 at 00:17