amol singh
amol singh

Reputation: 143

List iterator returning zero

i am trying to iterate records from a table using the list iterator but it is returning zero records . i have used a setter getter class and trying to fetch records into a jsp page

code is as follows :

java function :

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 code :

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 is running fine in sql , i checked and confirmed

below is the small segment from setter getter class 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;
}

Upvotes: 2

Views: 173

Answers (2)

Chandu D
Chandu D

Reputation: 501

you have to remove , from category and product using 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%'"

or you also try this one

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

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

Upvotes: 0

Panther
Panther

Reputation: 3339

Move prod.add(p); inside the while loop. As you are not adding object everytime. Also you need to create new object of p in loop everytime.

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

Upvotes: 4

Related Questions