It's not a secret anymore!
The moose likes JDBC and Relational Databases and the fly likes jdbc Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » JDBC and Relational Databases
Bookmark "jdbc" Watch "jdbc" New topic


Chandrashekhar Telang

Joined: Nov 28, 2003
Posts: 7

i urgently need to build a dynamic query builder using prepared statement
how an a dynamic select query having multiple parameters can be built?
For. e.g. select * from xyz where a=? AND|OR b=? AND|OR c=? where occurence of a,b,c can be known only at runtime from user selection of parameters to the query builder also the parameter types also could vary such as String, int or a double? also clauses AND or OR can occur in between the parameters. Any Help would be highly appreciated.
thanks in advance.

Adeel Ansari
Ranch Hand

Joined: Aug 15, 2004
Posts: 2874
Why using PreparedStatement is a must?
Jeanne Boyarsky
author & internet detective

Joined: May 26, 2003
Posts: 33117

I don't see this being easier with a Statement over a PreparedStatement. And a PreparedStatement caches the execution plans for when the dynamic SQL happens to be ths same.

Building a statement or prepared statement is just a matter of logic (in java) to assemble the pieces separated with AND/OR. I'm not sure I understand the question.

[OCA 8 book] [Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Other Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, TOGAF part 1 and part 2
James Carman
Ranch Hand

Joined: Feb 20, 2001
Posts: 580
Using PreparedStatements can be safer, though. Consider the case where you're substituting in values typed from the user on a webpage (or somewhere else). If they "Jim's Bar and Grill", you have to make sure you escape the ' character if you try to just build the SQL string dynamically. But, if you use a PreparedStatement and set the parameters, this is done for you.

James Carman, President<br />Carman Consulting, Inc.
Adeel Ansari
Ranch Hand

Joined: Aug 15, 2004
Posts: 2874
I was just asking the reason, nothing else.
If you can do it with Statement then you can also go with PreparedStatement. PreparedStatement is better.
I agree. Here's the link:
subject: jdbc
It's not a secret anymore!