Adding slash "\" character before quote "'" in a query

Ads
 

Adding slash "\" character before quote "'" in a query

Adding slash "\" character before quote "'" in a query Adding slash " \ " character before quote " ' " in a query During the inserting the records in the database if user enters the phrases like "What ' s your name?", database gives the error due

Adding slash "\" character before quote "'" in a query Adding slash " \ " character before quote " ' " in a query During the inserting the records in the database if user enters the phrases like "What ' s your name?", database gives the error due

Adding slash "\" character before quote "'" in a query 

     

Adding slash "\" character before quote "'" in a query 



During the inserting the records in the database if user enters the phrases like "What's your name?", database gives the error due to the presence of the "'" quote. So it is necessary to add slashes before the quote. For example if the user enters "What's your name?" then we will have to change it to "What\'s your name?" by placing the "\" character before the quote "'". Following program do this:

import java.util.*;

public class quote{

public String addSlashes(String str){
if(str==null) return "";

StringBuffer s = new StringBuffer ((String) str);
for (int i = 0; i < s.length(); i++)
if (s.charAt (i) == '\'')
s.insert (i++, '\\');
return s.toString();

}

public static void main(String args[]) {
quote qt=new quote();

System.out.println(qt.addSlashes("What's your name?"));
}

}


If you run the above code addSlashes function will add slashe ("\") before the quote "'" and the out put will be shown on the console.


You can use the following function in your java application to add the slashes.

public String addSlashes(String str){
if(str==null) return "";

StringBuffer s = new StringBuffer ((String) str);
for (int i = 0; i < s.length(); i++)
if (s.charAt (i) == '\'')
s.insert (i++, '\\');
return s.toString();

}


Next time I will show you how to use this in java applications.

Ads

Ads