Welcome!

Java Authors: Michael Sheehan, Maureen O'Gara, Jonny Defh, Suresh Krishna Madhuvarsu, RealWire News Distribution

Related Topics: Java

Java: Article

How Can I Escape Quotes in SQL Queries?

How Can I Escape Quotes in SQL Queries?

It depends on the SQL backend you're using, and how sincere you are. Basically, you'd want to convert every single quote to be double-single-quotes (i.e., O'Donnell becomes O''Donnell), which means writing a custom function.

That's ugly, and unnecessary. (Aren't you glad?)

If you use PreparedStatements, the JDBC driver will escape all data for you, for the specific database you're using. (This is important, as some DBs don't follow the "double single-quotes" rule mentioned above.) Example code:

PreparedStatement ps=conn.prepareStatement("insert into names values (?)");
ps.setString(1, "O'Donnell");
ps.executeUpdate();

Reproduced with permission of http://java.enigmastation.com/index The Undernet #Java Knowledge Base

More Stories By Joseph Ottinger

Joseph Ottinger, formerly editor-in-chief of JDJ (2003-4), is a consultant with Fusion Alliance in Indianapolis and is one of the contributors to the OpenSymphony project.

Comments (1) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
Andrea Lindsay 06/17/04 08:12:55 AM EDT

Thanks! This worked much better than a function.