Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

Java Strings and restricted characters

  Asked By: Abelerd    Date: Mar 28    Category: Java    Views: 1075
  

I am trying to insert a string containing quote marks into a
database. This requires me to insert the string into an SQL string.
Unfortunatly The SQL string uses quote marks as a restricted
character. This means that a quote mark in the string I am tring to
insert changes the syntax of the SQL string. I have written a routine
to parse them out before being inserted but I really need them.

Is there another solution?

I have had similar problems handling strings with quotes and speach
marks else where in my code.

I have also tried putting it though in unicode, doesn't work!

I'd like any suggstions on how to solve the problem.

Share: 

 

2 Answers Found

 
Answer #1    Answered By: Adali Fischer     Answered On: Mar 28

Usually you have to escape any quotes  in your SQL statement. You should
check the documentation for your SQL server to determine how to escape
quotes exactly. I am not sure whether the escaping mechanism is
specific to each database or if there is a standard.

In MySQL, for example, you escape the single or double quote  with a
backslash:

\'
\"

As for non ASCII characters, perhaps someone else can make some
suggestions, as I have no practical experience with it.

 
Answer #2    Answered By: Olga Kates     Answered On: Mar 28

Building quoted and escaped strings  in Java can be difficult when the
same sequences are the rule for the target (ie, the database engine).

Another db that uses this same pattern is Oracle, btw.

If you build a string  s in Java that contains escape sequences, you
must also escape (prefix with the \ character) each character that
might be recognized by the Java parser.

So if you want to send "XYZ" to the target as an escaped sequence
\"XYZ\" you'll have to add some additional escapes so Java won't act
on the characters  first:
\\\"XYZ\\\"
Where \\ escapes the escape character so Java won't act on it.
\" does as Anthony explained, only here so Java won't act on it.
The sequence is repeated at the end.

Then, you put it into a Java string:
s = "\\\"XYZ\\\"";

This is where the declaration of contants can help clarify your
intent:

final String ESC = "\\"; // escaped escape
final String DQ = "\""; // escaped double quote

s = ESC + DQ + "XYZ" + ESC + DQ;

Well, I think it clarifies! ;-) Anyway, now s is ready to be included
as the parameter to the SQL or whatever. The escapes and quotes  will
be sent along with the text.

 
Didn't find what you were looking for? Find more on Java Strings and restricted characters Or get search suggestion and latest updates.




Tagged: