I have several instances where that a section of legacy sql statements is based on a dependency. for example.
if (x !=null) { SQL = 'SELECT z WHERE x > y'; } else { SQL = 'SELECT z WHERE x <= y'; } SQL2 = SQL + ' JOIN a ON b';
I am creating PreparedStatements out of this legacy code. What is the best-practice here. Should I create a PreparedStatement for the var SQL and nest it inside of SQL2 of should there be multiple PreparedStatements based on SQL2 without nesting, or something totlly different?
The code is much more complex than the example, as the SQL var is reused inside many long and complex SQL queries.
EDIT: Project Design requires using PreparedStatements, I don’t have the choice of using libraries at this moment.
>Should I create a PreparedStatement for the var SQL and nest it inside of SQL2
No
>Or should there be multiple PreparedStatements based on SQL2 without nesting
Yes
Furthermore: If you could create one string per query that would be better. I don’t really like to mix SQL with code. It makes it harder to debug and to understand, you can’t copy/paste to a SQL tool to test it easily. By separating the SQL from your code you’ll isolate your query from the operation ( the actual fetch ) and it would be easier to maintain. Plus if the code is not yours it will be a lot easier to understand.
It doesn’t matter it looks like your’re repeating strings, the point would be to simplify the statements as much as possible.
I would do something like this:
And then use it from your class:
While creating the class ‘DatabaseQueries’ you’ll find you’re repeating a lot of strings, I think it would be fine to susbtitute some part with other constants.
The point here is to make things simpler. This is the first step. In a second step you can create a class to create those queries that are really really complex, but probably YAGNI.
If the queries are too much you can replace it to load them from a ResourceBundle like in this question
I hope this helps.