我有一个bizzar问题。我正在读取数据库表并将每个列存储到结果集中,但问题是,结果集仅填充了最后一行值。例如,我有10行,我得到10行,但值与最后一行值一起复制。
实际数据库行(示例):
Id名称地址
1 A地址1
2 B地址2
3 C地址3
4 D地址4
5 E地址5
退出结果集
5 E地址5
5 E地址5
5 E地址5
5 E地址5
5 E地址5
我的代码如下:
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;
}
我在打电话:
@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();
}
仅供参考:这是使用JAVA JERSEY MySQL的休息api我正在使用Netbeans