Handling Escape Characters in JAVA
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Satra_Th
Posted On:   Monday, June 16, 2003 07:42 AM

I want to add the escape characters to all the apostophes in the SQL commands. Does anyone know an efficient function that can replace the charachter "'" to "''" in a String. Eg. String x = "Jame's garage"; should return "James''s garage"; and String x = "James's'g'a''"; should return "James''s''g''a''''"); I am looking for some efficeint program in java. I have tried in the following way but it didnt work: String x = ("Jame's Garage").replace('\'', '\'\'');    More>>

I want to add the escape characters to all the apostophes in the SQL commands. Does anyone know an efficient function that can replace the charachter "'" to "''" in a String.


Eg.
String x = "Jame's garage";
should return "James''s garage";


and String x = "James's'g'a''";
should return "James''s''g''a''''");


I am looking for some efficeint program in java.


I have tried in the following way but it didnt work:


String x = ("Jame's Garage").replace('\'', '\'\'');

   <<Less

Re: Handling Escape Characters in JAVA

Posted By:   Anonymous  
Posted On:   Monday, June 16, 2003 09:56 AM

I suggest you use PreparedStatements instead of "normal" Statements. With PreparedStatements, the JDBC-Driver takes care of character escaping.

If you for any reason need to escape characters anyway, you could use the following method:



/**
* Escape selected characters of a given string.
* @param str is the String to work on.
* @param chars is a String of characters that should be escaped.
* @param esc is the escape character.
* @return the escaped String.
*/
public static String escape(String str, String chars, char esc)
{
String result = str;
if ((str != null) && (chars != null) && (str.length() > 0))
{
StringBuffer resBuffer = new StringBuffer(str.length() + 16);
int len = str.length();
for (int i = 0; i < len; i++)
{
char actual = str.charAt(i);
if (chars.indexOf(actual) >= 0)
{
resBuffer.append(esc);
}
resBuffer.append(actual);
}
result = resBuffer.toString();
}
return result;
}
About | Sitemap | Contact