我正在尝试使用列表迭代器
迭代表中的记录,但它返回零
记录。我使用了 setter getter 类并尝试将记录提取到 jsp 页面中
代码如下:
java函数:
public List<product> getProducts()
{
List<product> prod=new ArrayList<product>();
try
{
conn = obj.connect();
String sql="select product.product_name , product.price , product.image_url "
+ "from category , product "
+ "where product.category_id=category.category_id and product.product_brand like 'LG%'";
rs=cs.executeQuery(sql);
while(rs.next())
{
p.setPname(rs.getString(1));
p.setPrice(rs.getString(2));
p.setImg(rs.getString(3));
}
prod.add(p);
}
catch(SQLException e)
{
e.printStackTrace();
}
catch(Exception k)
{
k.printStackTrace();
}
return prod;
}
jsp代码:
operations op=new operations();
product p=new product();
List<product> list=op.getProducts();
%>
<title>LG Mobiles</title>
</head>
<body>
<b><font color="blue">Total Records Fetched : <strong><%=list.size()%></strong></font></b>
QUERY 在 sql 中运行良好,我检查并确认
下面是 setter getter 类的一小段 product.java
public void setPname(String pname)
{
this.pname=pname;
}
public String getPname()
{
return pname;
}
public void setPrice(String price)
{
this.price=price;
}
public String getPrice()
{
return price;
}
最佳答案
移动 prod.add(p);在 while 循环内。因为您并不是每次都添加对象。另外,您每次都需要在循环中创建 p 的新对象。
while(rs.next())
{
product p = new product();
p.setPname(rs.getString(1));
p.setPrice(rs.getString(2));
p.setImg(rs.getString(3));
prod.add(p);
}
关于java - 列表迭代器返回零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31237891/