Dynamic SQL in Java
Posted on 2004-10-12
I am using prepared statement on one of my java calls to the database.
Here's is a sample of the same
String sql = "Select <table_nam>.<column_name> from <schema_name>.<table_name>
and <column_name_1> = ? " +
" and <column_name_2> = ? " +
" and <column_name_3> = ? ";
I set the parameters for aboe column as below
stmt.setString( 1, column1 );
stmt.setString( 2, column2 );
stmt.setString( 3, column3 );
column1, column2 and column3 values are passed to the method that has the above code block.
How to make this SQL dynamic ?. If column1, column2 and column3 has particular values (say "X") I DO NOT want to add
in the SQL. For that I have an if statment and populate sql without problem. BUT i have to incorporate many permutations
for setting the statement block, so that it matches with the SQL string. How to do both things i.e generating SQL and setting values (when the values are conditional) in statements.
What is the best possible solution to have the code modular and more robust (avoiding lot of if's)