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.
SCJP2 , SCWCD
Anonymous
Ranch Hand
Joined: Nov 22, 2008
Posts: 18944
posted
0
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 ]
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
Joined: May 01, 2002
Posts: 5
posted
0
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
posted
0
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: