5

I've searched the site but haven't found exactly what I need. I have an SQL statement

String unformattedSQL = "select id, name, address, zip    from   schema123.person  where name like '%stu%'";

I'm looking for a method like formatSQL(sqlString) that gives me the formatted version of my original SQL statement, such that

String formattedSQL = formatSQL(unformatted);
System.out.println(formattedSQL);

will give me the following text (with correct indentation)

SELECT id, name, 
       address, zip 
FROM schema123.person 
WHERE name LIKE '%stu%'

The original SQL statement is actually very long and is dynamically generated by another method (I cannot change this method), so there's no way I can put the SQL in an external file. After the SQL is executed, I need to put it in a log file. I want the SQL statement to be formatted in the log file.

What is the best way to do this? And to generalize the problem, how to do this for another syntax like XML, C#, etc. Maybe something similar to Google Code Prettify but for Java ...

stupid
  • 55
  • 2
  • 6

1 Answers1

6

You can go for the SQLFormatter provided by apache openJPA project

Sanjeev
  • 9,876
  • 2
  • 22
  • 33
  • 2
    Thanks for your tips. It works but not like what I expected. The SQLFormatter only works well if the original SQL string is more or less well formatted. But in my case the query can be realy ugly, i.e inconsistent indentation, multiple levels of subqueries, blank lines after colon. I need this to be fixed in the manner Eclipse formats source code. Moreover it would be best if there's the possibility to define the formatting rules. – stupid May 21 '14 at 14:56