Reputation: 135
Hi this sql query is not working in some conditions.Whenever i write
query += " Price<? and Size<? and Type=?";
out of the if statement then it is working but when i put within the if statement then it doesn't work. And when i am trying print the variable query when it is outside the if statement then it show the message like this
select * from products where Price<? and Size<? and Type=?
I am not able to understand it please help me out this is the whole code`
public List<Products> Filter_Items(String[] Brand, String[] Flavour,float Price,float Size,String Type)
{
ResultSet rs;
List<Products> data = null;
PreparedStatement stmt;
try {
StringBuilder param = new StringBuilder();
if (Brand != null) {
for (String str : Brand) {
param.append("'").append(str).append("', ");
}
}
StringBuilder param1 = new StringBuilder();
if (Flavour != null) {
for (String str : Flavour) {
param1.append("'").append(str).append("', ");
}
}
String prm = param.toString().length() > 2 ? param.toString()
.substring(0, param.toString().length() - 2) : null;
String prm1 = param1.toString().length() > 2 ? param1.toString()
.substring(0, param1.toString().length() - 2) : null;
String query = "select * from products where ";
if(Price!=0 && Size!=0 && Type!=null && prm != null && prm1 != null)
{
query+="Brand in (" + prm + ") and Flavour in (" + prm1 + ") and";
query += " Price<? and Size<? and Type=?";
}
System.out.println("---------------------------------------------");
System.out.println(query);
stmt = DataBaseConnection.DBConn.getConnection().prepareStatement(query);
stmt.setFloat(1, Price);
stmt.setFloat(2, Size);
stmt.setString(3, Type);
rs = stmt.executeQuery();
if (rs != null) {
data = new ArrayList<Products>();
while (rs.next()) {
Products p = new Products();
p.setTitle(rs.getString("Ttile"));
p.setCategory(rs.getString("Category"));
p.setSubCategory(rs.getString("SubCategory"));
p.setSubCategoryTwo(rs.getString("SubCategorytwo"));
p.setPrice(rs.getInt("Price"));
p.setFlavour(rs.getString("Flavour"));
p.setSize(rs.getFloat("Size"));
p.setImage(rs.getString("image"));
p.setBrand(rs.getString("Brand"));
p.setInstock(rs.getString("instock"));
p.setInstockQty(rs.getInt("instockqty"));
p.setType(rs.getString("Type"));
data.add(p);
}
}
} catch (Exception e) {
System.out.println(e.getStackTrace());
System.out.println("----------------------");
System.out.println(e.getMessage());
System.out.println("----------------------");
System.out.println(e.getSuppressed());
System.out.println("----------------------");
e.printStackTrace();
System.out.println("Error aa gai bhai ");
return null;
}
return data;
}
User may not select the brand or size so the value of any of them may be null
so I have create different if
conditions. How to achieve this?
EDIT:
This code doesn't work when I don't select any value from my JSP. I'm getting NullPointerException
. This is the servlet code that calls my method:
public class My extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
float Price = 0, Size = 0;
Price = Float.parseFloat(request.getParameter("Price"));
Size = Float.parseFloat(request.getParameter("size"));
String Type = request.getParameter("type");
String[] Brand = request.getParameterValues("Brand");
String[] Flavour = request.getParameterValues("Flavour");
List<Products> data = new SessionBeanClass().Filter_Itemsl(Brand, Flavour, Price, Size, Type);
request.setAttribute("Products", data);
;
request.getRequestDispatcher("sample2.jsp").forward(request, response);
}
Upvotes: 1
Views: 2105
Reputation: 85779
To build the query dynamically, it is better to:
List<Object>
that will store all the parameters to pass to your query.The implementation will look like this:
List<Object> parameters = new ArrayList<>();
/*
Parameter to evaluate:
String[] Brand, String[] Flavour,float Price,float Size,String Type
*/
StringBuilder query = new StringBuilder("SELECT * FROM products WHERE 1=1");
if (Brand != null) {
query.append(" AND brand in (");
for (int i = 0; i < Brand.length; i++) {
query.append('?');
if (i < Brand.length - 1) {
query.append(',');
}
parameters.add(Brand[i]);
}
query.append(")");
}
if (Flavour != null) {
query.append(" AND Flavour in (");
for (int i = 0; i < Flavour .length; i++) {
query.append('?');
if (i < Flavour.length - 1) {
query.append(',');
}
parameters.add(Flavour[i]);
}
query.append(")");
}
if (Price != 0) {
query.append(" AND Price < ?");
parameters.add(Price);
}
if (Size != 0) {
query.append(" AND Size < ?");
parameters.add(Size);
}
if (Type != null) {
query.append(" AND Type = ?");
parameters.add(Type);
}
//prepare the statement
stmt = DataBaseConnection.DBConn.getConnection().prepareStatement(query);
//append the parameters
int i = 1;
for (Object parameter : parameters) {
stmt.setObject(i++, parameter);
}
//execute the dynamic query
rs = stmt.executeQuery();
if (rs != null) {
//rest of your code
}
From your edit. The problem is here:
Price = Float.parseFloat(request.getParameter("Price"));
Since you're not sending the data for "Price" parameter, request.getParameter("Price")
returns null
. Then, the code to be executed will be Float.parseFloat(null)
, which gives NullPointerException
for passing a null
value as parameter.
The solution is to store the result of request.getParameter("Price")
in a variable and evaluate the variable:
String priceParameter = request.getParameter("Price");
priceParameter = (priceParameter == null) ? "0" : priceParameter.trim();
Price = Float.parseFloat(priceParameter);
Similar for other variables that need conversion.
Upvotes: 2
Reputation: 135
public class My extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
float Price = 0, Size = 0;
Price = Float.parseFloat(request.getParameter("Price"));
Size = Float.parseFloat(request.getParameter("size"));
String Type = request.getParameter("type");
String[] Brand = request.getParameterValues("Brand");
String[] Flavour = request.getParameterValues("Flavour");
List<Products> data = new SessionBeanClass().Filter_Itemsl(Brand, Flavour, Price, Size, Type);
request.setAttribute("Products", data);
;
request.getRequestDispatcher("sample2.jsp").forward(request, response);
}
Upvotes: 0