1

Possible Duplicate:
Java - escape string to prevent SQL injection

Hi.

I constantly am running into silly little issues with submitting an sql query to my database when the sql query includes a user written string (including random characters like '$%&).

Is there a standard function anywhere that converts the user text into sql friendly text for Java?

Thx

Community
  • 1
  • 1
rockit
  • 3,708
  • 7
  • 26
  • 36
  • Possible duplicate of a previously asked question, please see: http://stackoverflow.com/questions/1812891/java-escape-string-to-prevent-sql-injection – Andre Dec 25 '10 at 15:33

1 Answers1

7

The following advice is good for any language or framework: do not write your queries by concatenating strings, that's unsafe. Use parameterized queries instead.

In Java, parameterized queries are written with PreparedStatement. For instance:

PreparedStatement stmt = connection.prepareStatement("SELECT * FROM whatever WHERE id = ? AND name= ?");
stmt.setInt(1, 1000); // parameters starts at 1
stmt.setString(2, "'$%&");
ResultSet rs = stmt.executeQuery();
// ...

More details there: http://download.oracle.com/javase/tutorial/jdbc/basics/prepared.html

See also the documentation for PreparedStatement: http://download.oracle.com/javase/1.4.2/docs/api/java/sql/PreparedStatement.html

Etienne de Martel
  • 34,692
  • 8
  • 91
  • 111