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 ...

3
  • @DonRoby yes you're right Commented May 21, 2014 at 14:48
  • It would be nice if the ones that marks a question as a duplicate would provide links to the duplicate questions in the yellow notice above. That way we can find the info we need faster. Commented Sep 1, 2016 at 23:28
  • Marked as duplicate to a question without an accepted answer, good job guys Commented Aug 6, 2019 at 9:11

1 Answer 1

6

You can go for the SQLFormatter provided by apache openJPA project

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.