【问题标题】:List iterator returning zero列表迭代器返回零
【发布时间】:2015-09-23 03:07:32
【问题描述】:

我正在尝试使用 list iterator 从表中迭代记录,但它正在返回 zero 记录。我使用了 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;
}

【问题讨论】:

  • 您正在执行操作 op = new Operations() 然后访问它。你是如何让dopata进入op的?您不会仅通过创建新操作()来获取数据,对吗?

标签: java jsp arraylist iterator


【解决方案1】:

移动 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);
  }

【讨论】:

  • 我试过了,但它不起作用..同样的结果..(也尝试了循环内的对象)
  • 通过直接在数据库上运行检查您的查询是否返回行
  • 现在它正在返回记录,但它是iterating only the last record 3 times!!
  • 你有没有在循环 product p = new product(); 中添加这一行??
  • 我没明白为什么我们需要在每次迭代中创建一个新对象...but it is working FINE
【解决方案2】:

您必须使用 as 从类别和产品中删除 ,

String sql="select product.product_name , product.price ,  product.image_url "
           + "from category as product "
           + "where product.category_id=category.category_id and   product.product_brand like 'LG%'"

或 你也试试这个

prod=cs.executeQuery(sql);
Iterator it=prod.iterator;

while(it.next())
{
---------------
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-16
    • 2014-10-23
    • 1970-01-01
    • 2014-11-27
    • 2014-02-01
    相关资源
    最近更新 更多