2

Is there a built-in way to escape user input in java using the JDBC? Something similar to the php version mysql_real_escape() function. What's the best way to validate input?

2 Answers 2

15

If you mean how do you make sure user input can't be used in SQL injection attacks, the way to do this (and the way all SQL should be written in JDBC) is using Prepared Statements. JDBC will automatically handle any necessary escaping.

http://java.sun.com/docs/books/tutorial/jdbc/basics/prepared.html

1
  • +1: Always Use Bind Variables! "Escaping" the input is to assemble dynamic SQL statements is dumb for many reasons.
    – S.Lott
    Sep 28, 2008 at 13:06
0

Just to add to the suggestion by @skaffman, PreparedStatements solve the issue for the majority of applications. However, there are some applications where (parts of) SQL statements (as opposed to just parameter values) are taken from user input (for example, a URL parameter containing the ORDER BY clause). Just make sure you sanitize those as well or, better yet, avoid such designs if possible.

1
  • This example isn't particularly compelling. if you want to have a user-injectable order-by clause, then have a fixed set of parameter which the application recognises and then has a look up table of column names for each permitted value.
    – skaffman
    Apr 17, 2009 at 14:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.