Wednesday, June 19, 2013

MySql Real Escape String in Java

Sometimes we have to do dynamic database queries which are very complex to build with Prepared Statements. In some languages there are very flexible methods to do "Mysql Real Escape". But I was unable to find one on Java. So I started to look in the internet. There were a number of them suggested. But none of which could provide a complete escape or near complete scape. Then i kind of copy pasted them together to make this method. I guess this will do the trick. Please note, use this code on your own risk. I shall not be held responsible if  (hopefully not) anything goes wrong.


public static synchronized String getMysqlRealScapeString(String str) {
String data = null;
if (str != null && str.length() > 0) {
str = str.replace("\\", "\\\\");
str = str.replace("'", "\\'");
str = str.replace("\0", "\\0");
str = str.replace("\n", "\\n");
str = str.replace("\r", "\\r");
str = str.replace("\"", "\\\"");
str = str.replace("\\x1a", "\\Z");
data = str;
}
return data;
}