tags:

views:

192

answers:

3

Different database servers use different ways to quote and escape identifiers.

E.g. "foo bar" vs `foo bar` vs [foo bar], or "10""" vs "10\"", or identifiers such as FooBar or array need to be quoted for some databases but not for others.

Is there any API method that performs the quoting/escaping correctly for a given database connection? Or any alternative solution?

+2  A: 

Don't escape identifiers. Don't quote column values either - use bound queries with PreparedStatement. It's a lot safer from SQL injection attacks.

Paul Tomblin
What if the database I'm accessing uses identifiers that actually require quoting? PreparedStatement is great for passing values, but what about identifiers?
aditsu
You shouldn't be using names that need quoting. Yishai's answer is pretty on the mark.
Paul Tomblin
That's good when I can choose the names myself, but it's not always the case. There are legacy databases and many other situations, plus I may be writing some generic code that doesn't know the actual names (e.g. they're passed as parameters).
aditsu
+4  A: 

I think the answer to your question is that if you are writing a database neutral application using JDBC, then you need to use database neutral names, and not things that require special escaping per database vendor.

There is nothing I know of in the JDBC which supports that. A ORM product will deal with such things.

Edit: If you are writing an ORM, then I would think need a seperate SQL generation class for each supported database, just to handle the various syntax involved, so you would have to write that. You can certainly look at the source code of the various open source ORM's out there and see how they handle it.

Yishai
Good point about database-neutral names, but surprises can still appear (e.g. a certain identifier may not be acceptable in another database).Also, what if I'm.. actually writing an ORM? Would it require a separate hand-coded quote/escape implementation for each supported database?
aditsu
Stick to the rules for identifier naming in the SQL standard. Those will work anywhere.
Paul Tomblin
+2  A: 

Have a look at

DatabaseMetaData.getIdentifierQuoteString()

I never used it but it sounds good :-)

getExtraNameCharacters() could also be of some help

Carlos Heuberger
Not a complete solution, but definitely useful!
aditsu