Skip to Main Content

Java Database Connectivity (JDBC)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

quoting values

843854Aug 2 2004 — edited Aug 3 2004
This seems awfully elementary but I wonder if others have a better answer than I do.

Like many, I'm sure, I routinely build SQL statements with code, often including literal string values. But if a literal value includes quotes, you have to escape these. For example, suppose you write:

stmt.executeQuery("select * from customer where lastname='"+name+"'");

Great if the name is "Smith", but if the name is "O'Malley" you get SQL syntax errors.

I've gotten around this in two ways:

1. Use a PreparedStatement and setString to get the values in.
2. Write a function to massage the string, namely, put quotes around it and escape any embedded quotes. I generally call this "q" or some such so I can write concise code, like:

stmt.executeQuery("select * from customer where lastname="+q(name));

Is there a "right answer" to this? I hate to have to write my own function to do the escaping: What if I switch database engines and it has a different method of doing the escapes? Indeed, I've already had to deal with this: I wrote a similar "q" function to massage dates, but I need different versions for mySQL, MS Access, and SQL Server. Okay, put it all into a function and you only have to change one place when you swap engines, but still, it just seems that something like internal date formats in the database engine shouldn't be my problem: I should just give a SQL.Date object and it should work. But I can't find a built-in function, other than using PreparedStatement. Maybe PreparedStatement is the right answer, but I worry that,

a) When I'm only doing it once, I'm now making two trips to the DBMS instead of one, which maybe is a trivial problem, so more important ...

b) Sometimes the query generation is complex, like

StringBuffer sql="select * from order where ";
if (byname)
sql.append("custname="+q(name));
else
sql.append("custid="+q(id));
if (timerange)
sql.append(" and shipdate>="+q(fromdate)+"and shipdate<="+q(thrudate));

... and so on. I've had a few where there were half a dozen conditions that changed what fields were included in a query. To do this with a PreparedStatement would make me then test all the conditions a second time, which makes the code hard to maintain.

How are others dealing with this?
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Aug 31 2004
Added on Aug 2 2004
2 comments
68 views