Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

working with variable number of parameters in a preparedStatement

I'm creating a search form for my application.
In it user selects fields that should be used in filtering data.
the number fields is variable so I don't know how many ? should be in where clause of SQL query.
How can I use preparedStatement with variable number of conditions in where clause?

Thanks

like image 677
Ariyan Avatar asked Sep 30 '12 10:09

Ariyan


People also ask

Which methods on the PreparedStatement can be used to bind the parameters?

You must supply values for every parameter before executing the SQL statement. The setXXX() methods bind values to the parameters, where XXX represents the Java data type of the value you wish to bind to the input parameter.

Is PreparedStatement is less efficient than Statement?

PreparedStatement provides different types of setter methods to set the input parameters for the query. PreparedStatement is faster than Statement. It becomes more visible when we reuse the PreparedStatement or use it's batch processing methods for executing multiple queries.


2 Answers

if you want to add variable number of conditions in where clause use StringBuilder (StringBuffer if its multithreaded env.) and and run time depending upon your conditions concate/append to your string.

like

StringBuilder query = new StringBuilder("Select id, name from Student ");


if(args >0)
{
    query.append(" where "); //and add more args.

and later create prepared statement with this query by converting it to string

PrepareStatement(query.toString());
like image 55
rbhawsar Avatar answered Nov 14 '22 22:11

rbhawsar


PrepardStatements don't support variable numbers of conditions. What some frameworks do, is they cache each PreparedStatement in a Map where the key is the query.

So each time you want to run a query, you need to build the string to create the PreparedStatement, check if you have it in the map (and reuse it) or create a new one, and add it to the map.

like image 38
Augusto Avatar answered Nov 14 '22 23:11

Augusto