aspose file tools*
The moose likes JDBC and the fly likes Vector and JDBC problem? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Databases » JDBC
Bookmark "Vector and JDBC problem?" Watch "Vector and JDBC problem?" New topic
Author

Vector and JDBC problem?

deepak mag
Greenhorn

Joined: Oct 11, 2000
Posts: 4
Hi,
I am looping through a ResultSet to set properties of an Class(cl). Then I add each class to the vector(vt) by casting the cl into Object. But when I try to retrieve elements from the vector. I only get one element as though all the elements in the vector are occupied by only one element.
Tell me how to retain the values(Objects) in the vector?
Carl Trusiak
Sheriff

Joined: Jun 13, 2000
Posts: 3340
Please post portions of your code where you are doing the key portions ie.
set cl values from resultset, adding the class to the vector and reading the vector.
any thing else that may be in question.


I Hope This Helps
Carl Trusiak, SCJP2, SCWCD
deepak mag
Greenhorn

Joined: Oct 11, 2000
Posts: 4
Here I set the properties and load the vector
aud is an Object
vt_aud is the vector
while(rs.next())
{
aud.setFirstName(rs.getString(1));
aud.setLastName(rs.getString(2));
aud.setEmail(rs.getString(3));
vt_aud.add((Object)aud);
}
To retrive
for(int i=0;i<vt_aud.size();i++)>
{
aud = (audience)vt_aud.elementAt(i);

firstname = aud.getFirstName();
lastname = aud.getLastName();
email = aud.getEmail();
System.out.prinln(firstname);
}
The problem is it prints only the last record of the resultSet.
Thanks for help.
DM
Jeroen Wenting
Ranch Hand

Joined: Oct 12, 2000
Posts: 5093
Try adding aud = new WhateverClassAudIs(); as the first statement inside the while() loop.
I made the same mistake once and ended up with 50 times the same entry in the Vector. What happens is that not actual Objects are stored, but references to Objects. What you are doing here is creating a single Object, then changing it all the time. The reference you store is always the same, so each time you retrieve it you get the same Object back.

while(rs.next())
{
aud = new Aud();
aud.setFirstName(rs.getString(1));
aud.setLastName(rs.getString(2));
aud.setEmail(rs.getString(3));
vt_aud.add((Object)aud);
}

42
Frank Carver
Sheriff

Joined: Jan 07, 1999
Posts: 6920
This is fairly simple once you realize that Java only stores references to objects in collections such as Vector. If you want to store several different objects in the Vector, you need to make sure each one is a separate object, not just the same object re-used each time. Try this version:

or, if you have control over the "audience" class, you can add a constructor and simplify the loop:


Read about me at frankcarver.me ~ Raspberry Alpha Omega ~ Frank's Punchbarrel Blog
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Vector and JDBC problem?