working with variable number of parameters in a preparedStatement

浪尽此生 提交于 2019-12-19 08:05:17

问题


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


回答1:


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.




回答2:


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());


来源:https://stackoverflow.com/questions/12660555/working-with-variable-number-of-parameters-in-a-preparedstatement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!