This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes JDBC and the fly likes Inserting strings with quotes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Databases » JDBC
Bookmark "Inserting strings with quotes" Watch "Inserting strings with quotes" New topic

Inserting strings with quotes

Carey Brown
Ranch Hand

Joined: Nov 19, 2001
Posts: 173

Is there an escape sequence that you can use to insert a string that contains a single quote? e.g.; "Carey's data". I tried a backslash but it didn't work, the backslash actually ended up in the database.
Jamie Robertson
Ranch Hand

Joined: Jul 09, 2001
Posts: 1879

The easiest way is to use a PreparedStatement instead of Statement. PreparedStatements automatically escape these troublesome characters. The other method is to escape single quotes with another single quote:
"insert into ... values ( "Sam", "O''Reilly" )
this will insert "O'Reilly" into the database.
Dorothy Finkel-Laverty
Ranch Hand

Joined: Nov 24, 2001
Posts: 51
Jamie - is that two single quotes between the O and R? Or a double quote?
Jamie Robertson
Ranch Hand

Joined: Jul 09, 2001
Posts: 1879

you've probably figured this out by now, but you are right, it should be:
"insert into ... values ( 'Sam', 'O''Reilly' )
this will insert O'Reilly into the database.
Adam Hardy
Ranch Hand

Joined: Oct 09, 2001
Posts: 565
O'Really? ;-)
It'll mess up your HTML & Javascript too if you're not careful.

I have seen things you people would not believe, attack ships on fire off the shoulder of Orion, c-beams sparkling in the dark near the Tennhauser Gate. All these moments will be lost in time, like tears in the rain.
Consider Paul's rocket mass heater.
subject: Inserting strings with quotes
Similar Threads
Escape Character in String Parsing
Regular expression confusion
EL Escape Character?
quote inside quote inside quote
Regex splitting on carat symbol