嗨,这个 sql 查询在某些情况下不起作用。每当我写
query += " Price<? and Size<? and Type=?";
在 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);
}
最佳答案
要动态构建查询,最好:
- 根据自己的字段评估每个字段
- 有一个
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"));
由于您没有发送“价格”参数的数据,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);
与其他需要转换的变量类似。
关于java - jsp中过滤记录的sql查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23789957/