Welcome!

Java Authors: Hari Gottipati, Tad Anderson, Yakov Fain, Pat Romanski, Colin Walker

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

I am a software evangelist for GigaSpaces technologies, as well as a writer and musician. I've been the editor-in-chief of Java Developer's Journal and TheServerSide.

GigaSpaces Technologies is a leading provider of a new generation of application platforms for Java and .Net environments that offer an alternative to traditional application-servers. The company's eXtreme Application Platform (XAP) is a high-end application server, designed to meet the most demanding business requirements in a cost-effective manner. It is the only product that provides a complete middleware solution on a single, scalable platform. XAP is trusted by Fortune 100 companies, which leverage it as a strategic solution that enhances efficiency and agility across the IT organization.

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.