In my Java code, I have something like this :
ResultSet rs = statement.executeQuery(
"SELECT a,b,c FROM foo -- here starts the long query"+
" -- that is not yet finished " +
" -- that still has something to say... "+
" -- now the end !"
);
I would like to clean up my code like this :
ResultSet rs = statement.executeQuery(all_queries.getQuery("The very long one"));
I have read that ResourceBundle
is for localization. So I don't think it matches in my case.
What should all_queries
be ?
EDIT : The most important thing for me is to clean up the code.
add index to each column and try (until you find the best one) try to change the primary key's index type - try Clustered instead of Non-Clustered. try to create a view upon this table and query from the view instead.
You can use a left outer join, or a not exists clause. Both are quite generic SQL solutions (don't depend on a specific DB engine). I would say that the latter is a little bit more performant (not by much though).
I would put it in a file with an sql extension and implement Queries
like:
Queries {
static public String getQuery(String name) {
return loadResource("/com/example/queries/" + name + ".sql");
}
}
User:
conn.prepareStatement(Queries.getQuery("my_query"));
Of course that's only one way to do it. You can make Queries
return Statement
, or even use a dynamic proxy to mask it behind a simple Java interface (where proxy handler could create statement, set parameters and run query). Your mileage may vary.
Added benefit: sql files have syntax coloring and are way easier to maintain than Strings in Java.
Since you need a mapping from a key (name) to value (long query), which is achieved using a dictionary (aka map, associative array) datastructure.
You should store your configuration in a file, separate from your code. I recommend the .ini configuration format, which is very readable, can be divided into sections, and has good parser for almost any computer language.
Your configuration file will look like:
[users_queries]
find_max_user_id = SELECT max(id)
FROM users
WHERE ...
name = query
...
...
Using the ini4j
module, getting your queries would be as easy as:
Ini.Section section = ini.get("users_queries");
String query = section.get("find_max_user_id");
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