Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Java equivalent of Perl's qq operator?

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?

like image 594
jeph perro Avatar asked Jul 31 '10 00:07

jeph perro


1 Answers

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.

like image 61
bakkal Avatar answered Sep 18 '22 10:09

bakkal