views:

912

answers:

3

Is there a Java equivalent to PHP's mysql_real_escape_string() ?

This is to escape SQL injection attempts before passing them to Statement.execute().

I know I can use PreparedStatement instead, but let's assume these are one shot statements so preparing them will result in lower performance. I've already changed the code to use PreparedStatement but given the way the existing code was structured, an escape() function would make the code changes much simpler to review and maintain; I prefer easy to maintain code unless there is a compelling reason for the extra complexity. Also PreparedStatements are handled differently by the database, so this could expose us to bugs in the database that we haven't run into before, requiring more testing before releasing to production.

Apache StringEscapeUtils escapeSQL() only escapes single quotes.

+3  A: 

Do not assume that PreparedStatements are slower. Try it, measure it, and then judge.

PreparedStatements should always be used in preference to Statement, pretty much without exception, especially when SQL injection attacks are what you're trying to avoid.

skaffman
+2  A: 

The only sensible way to avoid SQL injection is to use prepared/parameterized statements.

For example the PreparedStatement you are trying to avoid for some reason. If you do one-shot statements, the time to prepare them should be negligible ("one-shot" and "performance-critical" is a contradiction, IMHO). If you do things in a loop, prepared statements even cause performance to increase.

Tomalak
+5  A: 

As far as I know, there is no "standard" way to do it.

I strongly suggest using prepared statements despite your current concerns. The performance impact is going to be negligible - we have a similar situation with several thousand statements per second - most of them one-shots as well.

The security you gain should be weighed much higher than a performance problem you have not even seen yet. In my opinion this is a clear situation of "Don't optimize prematurely".

In any case should you really find out later that you run into performance problems, make sure that the prepared statements are really the cause by profiling carefully and then look for alternatives. Till then you should save yourself the hassle of trying to get the escaping right.

This is even more important as I infer you are developing some sort of public facing site - internal apps seldom get enough traffic to be concerned about performance anyway.

Daniel Schneller
Thank you for starting by answering the question I asked!
Kieran Tully
You're welcome :)
Daniel Schneller