working with variable number of parameters in a pr

2020-03-21 09:51发布

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

2条回答
祖国的老花朵
2楼-- · 2020-03-21 10:24

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());
查看更多
【Aperson】
3楼-- · 2020-03-21 10:33

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.

查看更多
登录 后发表回答