I have a database server communicating with a Java application server using JDBC. I want to store data from the database ResultSet into Java variables.
Here's my Java class, HRPeople:
public class HRPeople {
public int elements;
public String[] FirstName;
public String[] LastName;
public String[] Email;
public int[] Salary;
}
I currently use this class to store data from ResultSet, as follows:
query = "SELECT first_name, last_name, email, salary FROM HR.Employees where rownum < 6";
rset = stmt.executeQuery(query);
while (rset.next()) {
returnHRdata.FirstName[ii] = rset.getString("first_name");
returnHRdata.LastName[ii] = rset.getString("last_name");
returnHRdata.Email[ii] = rset.getString("email");
returnHRdata.Salary[ii] = rset.getInt("salary");
ii = ii + 1;
}
The problem with the above scenario is that the primitive arrays require me to know the number of rows in the ResultSet so that I can properly initialize those arrays. So what I want to do is use an ArrayList instead. How would I modify the above scenario to do this?
Here's my initial attempt (is this close)? Is HRPeople.java file shown above even used in this scenario?
query = "SELECT first_name, last_name, email, salary FROM HR.Employees where rownum < 6";
rset = stmt.executeQuery(query);
List<HRPeople> returnHRdata = new ArrayList<HRPeople>();
while (rset.next()) {
returnHRdata.FirstName = rset.getString("first_name");
returnHRdata.LastName = rset.getString("last_name");
returnHRdata.Email = rset.getString("email");
returnHRdata.Salary = rset.getInt("salary");
returnHRdata.add;
}
UPDATE 1:
If I add to the code the following,
return returnHRdata;
I get the following error (any idea why?):
myClass.java:213: incompatible types
found : java.util.List<HRPerson>
required: java.util.ArrayList<HRPerson>
return returnHRdata;
^
1 error
create a class HRPeople, which has firstname, lastname.... attributes, and declare getter, setters method.
then:
You probably want to first define an HRPerson like this:
Then your main code would look like:
Instead of storing an array of each property in your object, make a single object to describe a given entity in the table.
Create a list of this type, allowing you to store the results.
Finally, fill it by creating new objects for each row in your table.
Convert this:
to:
and:
Now it should be easy:
You can improve this code by using a lowerCase letter for your first char of your fields and using getters and setters to access them.
Close...
You of course must define the setXXXX methods on the HRPerson class. Oh yeah, and do what Thomasz suggested.