Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem inserting a single quote (')

 
Imran Ahmed Khan
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • 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.
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi! You must escape the "'" character. Because SQL thinks that the string end when it comes to "'" char.
public String SQLEscape( String pStr ){
String mStr;
mStr = pStr.replace( "'" , "''" );
return mStr;
}
That's it!
[ May 05, 2002: Message edited by: Mathias P.W Nilsson ]
 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There was also a reply to your dulpicate thread in the JSP forum here
Please don't post the question in multiple forums.
Dave
 
Craig Demyanovich
Ranch Hand
Posts: 173
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mathias,
This code is invalid based on the API docs for Java 2 SDK 1.3.1 and 1.4.0. The only replace() method documented is one that takes two characters, not two strings. Have you actually used this code?
Imran,
Why doesn't PreparedStatement work? Using PreparedStatement relieves you of the burden of escaping single quotes in parameters that contain them. That's the point of PreparedStatement.
Craig
 
Imran Ahmed Khan
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Mr. Mathias, u can see that i have used prepare statement, but it doesnt work in it either.
 
Craig Demyanovich
Ranch Hand
Posts: 173
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's code that I wrote quite some time ago. I was just commenting/uncommenting to use different methods. I did not have to escape single quotes when using PreparedStatement, as the comment in the code indicates. Note that these statements won't be committed to the table unless you uncomment the call to commit().
Here's the table that I used:

Here's the class:

Craig
[ May 06, 2002: Message edited by: Craig Demyanovich ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic