• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Dynamic SQL Query Doubt

 
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi friends
Please give me a solution for my doubt.
I am Creating a dynamic SQL query such that if the user selects any value from the picklist then that I set the value in PreparedStatement using the following statement.
For simplification, I write the simple query but the actual query is big.
I am using Prepared Statement to set the value.
DBSQL Query = "select * from table1 where id=?"

StringBuffer sb = new StringBuffer();
sb.append("select * from table1 where id=?");
ps = con.prepareStatement(sb.toString());
ps.setInt(1,value);
rs = ps.executeQuery();
Suppose if the User did not select any value then I need to return all the values from the table.
DBSQL Query = select * from table1 where id is not null
I do not know how to formulate the prepared statement such that it will match the exact DBSQL Query.
Give me a proper solution how to handle this kind of situation?
Thanks,
Kumaran.S
 
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Your best bet is to build the final query from 2 substrings:
A fixed part "select * from table1 " and a variable part that's either "where id=?" or "where id is not null" based on the selected value for the query.
 
He was giving me directions and I was powerless to resist. I cannot resist this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic