问题
I am trying to convert from MS Access to DerbyDB. However some varchar fields have 'special' characters, such as newlines, tabs, percent marks, foreign characters etc.
I created a quick method...
public String charCheck(String s)
{
errLog.add(1, "converting string from " + s);
s.replaceAll("'", "''");//an apostrophe is escaped with an apostrophy in Derby...
s.replaceAll("%", "\\%");//a percent sign
s.replaceAll("\\s+n", " ");//whitespace characters (newlines and tabs etc)
s.replaceAll("/", "\\/");//the 'divide' \ character,
s.replaceAll("<", "\\<");//mathematical symbol less than
s.replaceAll(">", "\\>");//mathematical symbol greater than
errLog.add(1, "to " + s);
return s;
}//end method
Which I run whenever I determine that I need a varchar (or long varchar) data type. The strange thing is that my error log prints out the messages, but in the output whitespace characters do not appear to change (ie tabs and new lines, do not get converted to a simple space) and any apostrophe in the string is not replaced.
a sample of the output of this method produces the following.
converting string from 2. FIN DE L’ESSAI
to 2. FIN DE L’ESSAI
So the string remains obviously unchanged, which upsets derbyDB when I run the insert statement, also I am not finding any obvious documentation on the escape sequence for inserting multiple records into a table, I would like to use a statement then add the escape keyword after it, ie
stmt.execute("{call "+ sqlInsertStatement +"}{escape '" + escapeCharacter +"'" );
I also read from the docs that the escape keyword may not be usefull in the above statement, if so how can I te
I need to know where to go to sort the insert error that I get.
If I copy and past the insert statement directly into ij, then remove the special characters the record will insert fine, I just don't understand why it isn't being converted in the first instance.
I have also tried surrounding varchar and longvarchar fields with double quotes, but again derby kicks out an error saying that a double quote was found!
I want to get this sorted as I feel like I am so close...
Thanks in advance
回答1:
Strings are immutable, all operations you perform on them results new Strings. You need to assign current reference to new String.
Example:
s= s.replaceAll("'", "''");
If it is just replace, then replace() may be best option than using replaceAll()
回答2:
Instead of working through the String
, turn the String
into a char
array, then use a do...while loop to work through each char
in turn using if tests to replace each char. Then turn the array back to a String then return it
来源:https://stackoverflow.com/questions/12075355/search-java-string-for-special-characters-before-inserting-into-derbydb-varcha