Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

SQL Safe String

Status
Not open for further replies.

hemajb

Programmer
Sep 26, 2003
19
IN
I would want to make a string sql safe , so how do i handle strings which have ' and \ ??
can i achieve this using replaceall method in java.lang.String to replace all ' and \ with sql safe value. could someone help me on this
 
There are a couple of ways of doing this :

Code:
// Using String methods
String one = "ab'cd";
System.out.println(one.replace('\'','Q'));

String two = "ab\\cd";
System.out.println(two.replace('\\','Q'));

// Using java.util.regex package :
String REGEX = "\'";
String INPUT = "abc'd.";
String REPLACE = "T";

Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(INPUT);
System.out.println(m.replaceAll(REPLACE));

The ' and \ characters must be "escaped" because they can signify something other than a normal character (there is some fancy word for it, but I cannot think of it right now)(
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top