Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!
    Bookmark Topic Watch Topic
  • New Topic

Using JDBC how to put single quotes(')

Imran Ahmed Khan
Posts: 5
  • Mark post as helpful
  • send pies
  • Report post to moderator
I am having this problem with JDBC ... Using INSERT INTO statement i want to insert a row in my database and the variables that contain data might contain a single quote (') within them ... whenever i use a single quote in any of the text feilds that are to be inserted in the database i get an error i.e Misssing Operator or something like that, without any quotes the statement is working correctly..........
So please if anyone can tell me how to insert a value in the database which contains a single quote(').... here is the code. I am using a class which has this function.

ernest fakudze
Ranch Hand
Posts: 216
  • Mark post as helpful
  • send pies
  • Report post to moderator
Okay Imran, I've experienced the same problem myself before. Here is a a piece of code that should do the trick.
* replaceAll() - Replace all occurences of old string with new string in
* a given source string.
public static String replaceAll(String source, String oldString, String newString) {
int idx = 0;
while ( (idx = source.indexOf(oldString, idx)) >= 0 ) {
source = source.substring(0, idx) + newString +
source.substring(idx + oldString.length());
idx += newString.length();
} // end while.
return source;
}// end replaceAll().

* wrapField() - Wraps a field with single quotes if needed.
public static String wrapField(String value) {
// If there is a single quote in the string, replace it with 2 single quotes.
if (value.indexOf("'") >= 0) {
return (replaceAll(value, "'", "''"));
} // end if
return value;
} // end wrapField().
All you gotta do is to call the wrapField() method in your insert stmt for the fieldname that contains a single quote e.g....
insert into tblName(...) values() ... you get my drift. I use this code all the time because it does the trick.
Michael Ernest
High Plains Drifter
Posts: 7292
Netbeans IDE VI Editor
  • Mark post as helpful
  • send pies
  • Report post to moderator
This topic has been cross-posted in the JDBC forum, where it is appropriate to the theme. Since both topics have inspired replies, I am closing this one but not moving it. Please continue this discussion in JDBC as you wish, and please refrain from posting the same issue in multiple forums.
[ May 05, 2002: Message edited by: Michael Ernest ]
    Bookmark Topic Watch Topic
  • New Topic