I have a very long string which includes many new lines ( it's a really long SQL statement ).
The SQL is easier to read when I break it up with newlines. But from time to time, I need to copy the sql statement from code to paste into sql developer.
In Perl, I always loved the qq operator, which you can use in place of double quotes:
You use it something like this:
$myString = qq{
SELECT *
FROM table_a a
JOIN table_b b ON a.id = b.id ... etc
};
Is there an equivalent in JAVA? I find it awkward to have to break up the string in chunks like this:
String myString = " SELECT * " +
" FROM table_a a " +
" JOIN table_b b ON a.id = b.id ... etc ";
and it's hard to copy the SQL statement from code. I end up having to remove all the quotes and +'s
Is there a Java equivalent? Or is there a better trick to putting readable, copy-able SQL statements in Java code?
Multi-line Strings in Java
Is there a Java equivalent?
At the time of writing I do not think so. However there is a proposal to include multi-line Strings in Java.
Or is there a better trick to putting readable, copy-able SQL statements in Java code?
Putting parameters into SQL queries through concatenation isn't a very good idea. There are classes and API to help you form queries.
"Query Wrappers"
Wrappers can enhance readability, for example in JDOQL (JDO), you can create a query by using setWhere()
, setLimit()
, setDistinct()
etc.
Query q = pm.newQuery (...);
q.setWhere(...);
q.setRange (...);
q.setOrdering (...);
q.setLimit(...);
q.newParameter(...); // declare a query parameter
q.execute(34.5); // execute the SQL query with a parameter
For JPA, you can read JPQL.
if you are using plain JDBC, you might also have a look at PreparedStatement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With