File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes JDBC and Relational Databases and the fly likes Dynamic SQL Query Doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Databases » JDBC and Relational Databases
Bookmark "Dynamic SQL Query Doubt" Watch "Dynamic SQL Query Doubt" New topic

Dynamic SQL Query Doubt

Kumaran Sowrirajan
Ranch Hand

Joined: Oct 15, 2001
Posts: 36
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());
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?
Jeroen Wenting
Ranch Hand

Joined: Oct 12, 2000
Posts: 5093
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.

jQuery in Action, 3rd edition
subject: Dynamic SQL Query Doubt
It's not a secret anymore!