Вы находитесь на странице: 1из 2

Hi guys,

I need a help. The situation is next: I’m trying to store some results of ResultSet into ArrayList. Unfortunately, when I’m
retrieving the data from ArrayList, the result, which I’m getting, is only the last row of a table. The result is repeating as
many times as ArrayList size is. Could somebody explain me why it happens?

There is a snippet of the code to get a data from the ResultSet and add it into ArrayList:

// Execute a query
String sql = "select * from user";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
ArrayList list = new ArrayList();
// Extract data from the result set
while(rs.next()) {

CustomerBean cb = new CustomerBean();


if(rs.getString("first_name")!=null)cb.setFirstName(rs.getString("first_name"));
if(rs.getString("last_name")!=null)cb.setLastName(rs.getString("last_name"));
if(rs.getDate("dob")!=null)cb.setDob(rs.getDate("dob"));

list.add(cb);

Another snippet of the code to retrieve the data from ArrayList:

for (int i = 0; i < cb.getUserData().size(); i++){

System.out.println("First -"+((CustomerBean)cb.getUserData().get(i)).getFirstName()); // hire an error

System.out.println("Last - "+((CustomerBean) cb.getUserData().get(i)).getLastName());// hire an error

System.out.println("Dob - "+((CustomerBean) cb.getUserData().get(i)).getDob());// hire an error

One thing you should change is the multiple calls on the same column to retrieve the columns value from your results set.
This can definately be problematic depending on the JDBC driver you're using.

I might suggest something like this:

// Execute a query

String sql = "select * from user";

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

ArrayList list = new ArrayList();

// Extract data from the result set

while(rs.next()) {

CustomerBean cb = new CustomerBean();

String firstName = rs.getString( "first_name" );

String lastName = rs.getString( "first_name" );


Date dateOfBirth = rs.getDate( "dob" );

if ( firstName != null )

cb.setFirstName( firstName );

if ( lastName != null )

cb.setLastName( lastName );

if ( dateOfBirth != null )

cb.setDob( dateOfBirth );

list.add( sb );

for (int i = 0; i < list.size(); i++){

System.out.println("First -"+((CustomerBean)list.get(i)).getFirstName());
// hire an error

System.out.println("Last -
"+((CustomerBean)list.get(i)).getLastName());// hire an error

System.out.println("Dob - "+((CustomerBean)list.get(i)).getDob());// hire


an error

Although this might not immediately solve your problem, it might help narrow down the area where the problem might
exist.