0

How to replace single quote in Java with Postgres?

select * from where id in ('<45646300.KDSFJJSKJSDF95'fdgdfgdfgd>', 'fdgdfgdg');

I always use params like

select * from where id = ?;

But in this case i have problem, where i have 'in' statement with string passed to it.

I wish to replace all dangerous chars

1
  • Better to provide a table name. :) Commented Apr 21, 2011 at 10:30

5 Answers 5

3

It would be better to continue using PreparedStatements rather than to escape characters manually.

In the case of IN clause you can generate a query with appropriate number of ?s dynamically.

String[] input = ...;

StringBuilder b = new StringBuilder();
b.append("select * from where id in (");
b.append("?"); // Assume that input contains at least one element
for (int i = 1; i < input.length; i++) b.append(", ?");
b.append(")");

PreparedStatement s = c.prepareStatement(b.toString());

for (int i = 0; i < input.length; i++) s.setString(i + 1, input[i]);
Sign up to request clarification or add additional context in comments.

Comments

1

Apache commons API provides multiples ways to remove dangerous chars for specific languages such as CSS, Javascript SQL, etc...

Take a look at this if it helps : http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/StringEscapeUtils.html

Comments

1

Use the standard SQL quoting for single quotes:

select * 
from the_table
where id in ('<45646300.KDSFJJSKJSDF95''fdgdfgdfgd>', 'fdgdfgdg');

So any embedded single quote needs to be written twice.

Comments

0

Did you try?

select * from TABLE_NAME where id in (?);

2 Comments

Yes. But i have array or string delimited by ','. String param = "'aaa', 'bbb', 'ccc'". I dont know how to pass it
like this: prepStat.setString(1, myString);
0

There's a page explaining the different options over here on the javaranch site

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.