Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

JDBC problems through j2ee application 1

Status
Not open for further replies.

mslane

Programmer
Dec 12, 2001
11
US
Does anyone know how to prepare a query statement so that the queries won't stall when certain characters are entered by a user. For instance ' " & % #. These characters all stall my queries. Is there a quick java fix that I can apply, or do I need to write a QueryPrepare class to run my statements through?

Thanks,
Matt
 
all you need to do is place a \ before the character

for example

String SQL = "Select * from table where ID = \""+ id +"\"";

will equal

Select * from table where ID = "id"
 
Do I have to write a method that adds a slash to all five of those characters for every sql statement I make? That's what I'm wondering, is there an easier way, or something that has already been written to run my queries through.

Thanks,
Matt
 
unfortunatley there isn't an SQL writing or anything like it in Java
 
The quoting rules might differ from DB vendor to DB vendor. The best way is to use prepared statements:

PreparedStatement ps = connection.prepareStatement("select * from table where ID = ?");
ps.setInteger(1, 1000);
ResultSet rs = ps.executeQuery();

The setXXXX methods of PreparedStatement fill in the "?" gaps in the SQL query.

For additional info see the online Java Tutorial from sun.
 
(Using j2sdk1.4.0) There is a method on string called replaceAll that accepts regexp. Using this you can do the following. I don't know the escape sequences for each character (only the quote), so I may be wrong with this. Please try it, correct it, and post it back here. Thanks! :)

(Coming from a Perl background, I'm a big fan of one-liners.)

public static String quoteSQL( String unquoted ) {
return ( unquoted.replaceAll("\\'", "\\'\\'").replaceAll("\\&", "\\\\\\&").replaceAll("\\%", "\\\\\\%").replaceAll("\\#", "\\\\\\#") );
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top