3

I'm searching for a Java standard library to escape strings before using them in a SQL statement. This is mainly to prevent errors and to prevent SQL injection, too. Unfortunately, I will not be able to use prepared statements as is is suggested in a lot of other threads.

Is there any standard library I can use? I've seen StringEscapeUtils at Apache Commons but I really don't know if this is state of the art.

Thank you very much in advance!

Gray
  • 115,027
  • 24
  • 293
  • 354
user1040128
  • 31
  • 1
  • 2
  • Apache Commons is the mature library. It may have it's short-comings, but you'd have hard time looking for a better OSS Java library for your purpose. – Victor Sorokin Nov 10 '11 at 16:19
  • Hi Victor, thank you very much for your thoughts. :) As there are no comments to the contrary, I think I'll use the Apache Commons (that was quick) ;) – user1040128 Nov 10 '11 at 16:28
  • 1
    Do NOT use Apache Commons StringEscapeUtils.escapeSql() because it does NOT correctly escape sql to prevent sql injections. It has been removed from version 3 (allegedly because they want to discourage people using that instead of PreparedStatements, which ARE safe). – user467257 Nov 05 '12 at 09:54

2 Answers2

2

This is a non-trivial problem and a critical one because of SQL injection security issues. I would instead consider using SQL ? type arguments instead of escaping. For example, to search for a particular string:

Instead of doing:

SELECT * FROM accounts
    WHERE name = 'escapedstring1' AND password = 'escapedstring2'

I'd use:

SELECT * FROM accounts WHERE name = ? AND password = ?

You will then need to pass in the injected strings (without any escaping needed) as arguments to your SQL methods. Here's how to do it using JDBC. Not sure if that would apply to you.

Something like:

String statement = "SELECT * FROM accounts WHERE name = ? AND password = ?";
try {
  PreparedStatement stmt = databaseConnection.prepareStatement(updateString);
  // notice that it is 1 based, not 0 (ick)
  stmt.setString(1, name);
  stmt.setString(2, password);
  ResultSet results = stmt.executeQuery();

Here's how ORMLite, my ORM library, does it as an example using a select argument.

Hope this helps.

Gray
  • 115,027
  • 24
  • 293
  • 354
  • Hi Gray, thanks for your advice. This looks pretty good to me! I'll check that. I have to figure out how much effort it will be to change the data access layer... Again, many thanks! – user1040128 Nov 10 '11 at 17:54
  • I wish I could rate you with a +1. But a pop-up tells me that I need at least 15 Reputation Points to rate +1. :( – user1040128 Nov 11 '11 at 09:29
1

You can use Apache Commons, it's the very mature project.

Victor Sorokin
  • 11,878
  • 2
  • 35
  • 51