*
The moose likes JDBC and the fly likes Escaping Characters in SQL Queries Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Databases » JDBC
Bookmark "Escaping Characters in SQL Queries" Watch "Escaping Characters in SQL Queries" New topic
Author

Escaping Characters in SQL Queries

Tapan Parikh
Greenhorn

Joined: Jun 28, 2001
Posts: 26

Im trying to figure out how I can escape special characters in string constants in my SQL Query.
Is there any utility function I can use to do this? In the lack of this, anyone have any idea of the list of chars that need to be escaped (i know ' and % for instance) and their escape sequences, so that I can write one myself?
I am connecting to an ACCESS DB using Sun's JDBCODBC Bridge.
(BTW, Right now I am somewhat regretting this decision and wishing I had gone w/ ADO instead, because of this and other char encoding issues... Just a little 2 cents)
Best, Tap
Jamie Robertson
Ranch Hand

Joined: Jul 09, 2001
Posts: 1879

The best idea that I have seen come from this discussion in previous postings is to use the PreparedStatement. This way, you do not have to worry about special characters. Special characters are dependant on which database vendor you use, which does not make your code portable. Have you tried the PreparedStatement instead of the Statement?
Jamie
Tapan Parikh
Greenhorn

Joined: Jun 28, 2001
Posts: 26

I dont think Java's JDBCODBC Bridge supports auto-escaping of chars in conn.prepareStatement. It just fires an exception when the query contains invalid chars...
Jamie Robertson
Ranch Hand

Joined: Jul 09, 2001
Posts: 1879

Here is a static method that I used before the PreparedStatement. The escape character in Oracle for ' was adding another single quote(''). You should replace the escape values to that of your database documentation.

I included the main method in it so you can see it run.
hope this helps,
Jamie
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Escaping Characters in SQL Queries
 
Similar Threads
Escape XML special characters?
double quotes in java
using prepare statements
Problem with escape chars...
Tabbing in console window