I am having a bizzar issue. I am reading database table and storing each column into resultset but the issue is, resultset populated with last row values only. For example, I have 10 rows I am getting 10 rows but values are replicated with last row values.
Actual Database rows (Example):
Id Name Address
1 A Address1
2 B Address2
3 C Address3
4 D Address4
5 E Address5
Getting out of resultset
5 E Address5
5 E Address5
5 E Address5
5 E Address5
5 E Address5
My code as follow in class:
public static ArrayList<Animal> getAllAnimals() throws Exception {
PreparedStatement query = null;
Connection conn = null;
ArrayList<Animal> results = new ArrayList();
try {
// connect to database
conn = Database.mySqlDBConn().getConnection();
// run a query
query = conn.prepareStatement("SELECT * FROM animal");
ResultSet rs = query.executeQuery();
while (rs.next())
{
String name = rs.getString("name");
String animal_order = rs.getString("animal_order");
String family = rs.getString("family");
String genus = rs.getString("genus");
String species = rs.getString("species");
String zoo = rs.getString("zoo");
int number_avilable= rs.getInt("number_avilable");
System.out.print(name);
Animal animal = new Animal(name,animal_order,family, genus, species, zoo, number_avilable);
results.add(animal);
}
conn.close();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if(conn != null) conn.close();
}
return results;
}
I am calling:
@Path("/animal/")
public class ZooController {
/**
*
* @return
* @throws Exception
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response title () throws Exception{
//ArrayList<Animal> animals = new ArrayList<>();
//animals.addAll(Animal.getAllAnimals());
//(Animal.getAllAnimals());
//System.out.println(animals);
return Response.ok(Animal.getAllAnimals()).build();
}
FYI: This is a rest api using JAVA JERSEY MySQL I am using Netbeans