嗨,这个SQL查询在某些情况下不起作用。无论何时我写
query += " Price<? and Size<? and Type=?";
out if if语句然后它正在工作但是当我放入if语句时它就不起作用了。当我尝试在if语句之外打印变量查询时,它会显示像这样的消息
select * from products where Price<? and Size<? and Type=?
我无法理解,请帮助我 这是整个代码`
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;
}
用户可能无法选择品牌或尺寸,因此其中任何一个的价值可能为null
,因此我创建了不同的if
条件。怎么做到这一点?
编辑:
当我从JSP中选择任何值时,此代码不起作用。我得到了NullPointerException
。这是调用我的方法的servlet代码:
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);
}
答案 0 :(得分:2)
要动态构建查询,最好:
List<Object>
,它将存储要传递给您查询的所有参数。实现将如下所示:
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
}
从你的编辑。问题出在这里:
Price = Float.parseFloat(request.getParameter("Price"));
由于您未发送&#34; Price&#34;参数request.getParameter("Price")
返回null
。然后,要执行的代码将为Float.parseFloat(null)
,这会使NullPointerException
传递null
值作为参数。
解决方案是将request.getParameter("Price")
的结果存储在变量中并评估变量:
String priceParameter = request.getParameter("Price");
priceParameter = (priceParameter == null) ? "0" : priceParameter.trim();
Price = Float.parseFloat(priceParameter);
类似于需要转换的其他变量。
答案 1 :(得分:0)
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);
}