0

All,

I am storing SQL queries as XML for my java application to improve maintainability.

Parts of my query require parameterisation, therefore I have created identifiers that I can use to replace with values when I create my query string.

e.g.

WHERE CB.callback_date >= TO_DATE('$LASTDATE$','DD/MM/YYYY')
  AND CB.callback_date < TO_DATE('$FROMDATE$','DD/MM/YYYY')

I have a function in my application that will replace these substrings.

public static String xmlQueryPrep(String prep)
{

    //add dates to query
    prep.replace("'$LASTDATE$'", "'20/10/2013'");
    prep.replace("'$FROMDATE$'", "'18/10/2013'");
    prep.replace("&lt;", "<").replace("&gt;", ">");
    return prep;    
}

For some reason it is replacing the ASCII codes for < and > but it is not replacing my markup

Output

WHERE CB.callback_date >= TO_DATE('$LASTDATE$','DD/MM/YYYY')
  AND CB.callback_date < TO_DATE('$FROMDATE$','DD/MM/YYYY')

Why is it not replacing correctly?

1
  • It looks like you're using string operations to build SQL. Are you aware just how poor an idea that really is? If you can use a parameterized prepared query or a (correctly-designed) named query instead, you'll avoid a lot of trouble! (Note that this is true independent of what language you use to prepare the query.) Commented Oct 20, 2013 at 19:04

1 Answer 1

7

Strings in Java are immutables.

An object is considered immutable if its state cannot change after it is constructed

If you take a look at the documentation, you will see that each method that is applied to a String to modify its content will return a new String.

You should do :

prep = prep.replace("'$LASTDATE$'", "'20/10/2013'");
prep = prep.replace("'$FROMDATE$'", "'18/10/2013'");
prep = prep.replace("&lt;", "<").replace("&gt;", ">");
return prep;  

Or even better (method chaining):

return prep.replace("'$LASTDATE$'", "'20/10/2013'")
           .replace("'$FROMDATE$'", "'18/10/2013'")
           .replace("&lt;", "<")
           .replace("&gt;", ">");
Sign up to request clarification or add additional context in comments.

4 Comments

In other words, string.replace(.....) returns a new string in which the replace operation has taken place, the old string is unaffected
Why is C++ different then with regards to strings?
Java is based on C/C++, but is s new/different language. There are many differences - thus is just one.
@serupticious Java's StringBuilder works a lot more like strings in C and C++, but it's (directly) used a lot less frequently.

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.