aspose file tools*
The moose likes JDBC and the fly likes Problem inserting a single quote (') Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Databases » JDBC
Bookmark "Problem inserting a single quote ( Watch "Problem inserting a single quote ( New topic

Problem inserting a single quote (')

Imran Ahmed Khan

Joined: May 01, 2002
Posts: 5
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.

Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
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

Joined: Mar 06, 2001
Posts: 13459

There was also a reply to your dulpicate thread in the JSP forum here
Please don't post the question in multiple forums.
Craig Demyanovich
Ranch Hand

Joined: Sep 25, 2000
Posts: 173
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?
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.
Imran Ahmed Khan

Joined: May 01, 2002
Posts: 5
Dear Mr. Mathias, u can see that i have used prepare statement, but it doesnt work in it either.
Craig Demyanovich
Ranch Hand

Joined: Sep 25, 2000
Posts: 173
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:

[ May 06, 2002: Message edited by: Craig Demyanovich ]
I agree. Here's the link:
subject: Problem inserting a single quote (')
Similar Threads
Using JDBC how to put single quotes(')
Doubt in the following code
Prepared Statement problem in my servlet's data manager
How to redirect to another jsp page using multi-part form?
Redirect to another page after inserting