code_junkie

What is the best-practice for nesting PreparedStatements?

Nov 13th, 2011
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.81 KB | None | 0 0
  1. if (x !=null)
  2. {
  3. SQL = "SELECT z WHERE x > y";
  4. }
  5. else
  6. {
  7. SQL = "SELECT z WHERE x <= y";
  8. }
  9.  
  10. SQL2 = SQL + " JOIN a ON b";
  11.  
  12. final class DatabaseQueries {
  13. public final static String SOME_SCENARIO = "SELECT z WHERE x > y JOIN A, B ";
  14. public final static String SOME_OTHER_SCENARIO = "SELECT z WHERE x <= y JOIN A, B";
  15. }
  16.  
  17. PreparedStatement pstmt = getCon().prepareStatement( getQuery() );
  18.  
  19.  
  20. private String getQuery() {
  21. if( x != null ) {
  22. return DatabaseQueries.SOME_SCENARIO;
  23. } else {
  24. return DatabaseQueries.SOME_OTHER_SCENARIO;
  25. }
  26. }
  27.  
  28. final class DataBaseQueries {
  29. // this one is private
  30. private final static String JOIN_A_B = " join A, B ";
  31. public final static String SOME_SCENARIO = "SELECT z WHERE x > y " + JOIN_A_B ;
  32. public final static String SOME_OTHER_SCENARIO = "SELECT z WHERE x <= y " + JOIN_A_B ;
  33.  
  34. }
  35.  
  36. <select id="queryName" parameterClass="com.blah.X"><!<[CDATA[
  37. SELECT z
  38. FROM a
  39. JOIN b ON a.id = b.foreign_key
  40. WHERE
  41.  
  42. <isNotNull property="value">
  43. x > y
  44. </isNotNull>
  45.  
  46. <isNull property="value">
  47. x <= y
  48. </isNull>
  49.  
  50. ]]></select>
  51.  
  52. String selectQuery =
  53. (new SelectQuery())
  54. .addColumns(t1Col1, t1Col2, t2Col1)
  55. .addJoin(SelectQuery.JoinType.INNER_JOIN, joinOfT1AndT2)
  56. .addOrderings(t1Col1)
  57. .validate().toString();
  58.  
  59. String sql = "yadda yadda yadda ? yadda yadda WHERE ";
  60. if (mystery condition 1){
  61. sql = sql + " page=?"
  62. }
  63. else if (mystery condition 2)
  64. {
  65. sql = sql + " ORDER BY ? "
  66. }
  67.  
  68. private static final String FIND_PAGE_QUERY = "...."
  69. private static final String ORDER_BY_QUERY =" ..."
  70.  
  71. if (mystery condition 1){
  72. return process(FIND_PAGE_QUERY, parameters);
  73. }
  74. else if (mystery condition 2)
  75. {
  76. return process(ORDER_BY_QUERY, parameters);
  77. }
  78.  
  79. SELECT z WHERE (? IS NOT NULL AND x > y) OR (? IS NULL AND x <= y)
Add Comment
Please, Sign In to add comment