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

1

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.