Java – what type of data structure should I use to save table rows?
•
Java
I'm a novice in Java. I just enter the query database So far, my results are in resultsetmetadata I think for each row in the dataset, should I add it to some form of collection? Can anyone tell me the best way?
Thank you, jonesy
Solution
Usually we have a class and a field corresponding to a table Then, whenever we have a (full) row in a result set, we create an instance of this class
Example:
Consider a table created like this:
CREATE TABLE customer (First_Name char(50),Last_Name char(50),Address char(50),City char(50),Country char(25),Birth_Date date);
A model class will look like this:
public class Customer {
private String firstName;
private String lastName;
private String address;
private String city;
private String country;
private Date date;
public String getFirstName() {
return firstName;
}
// getters for all fields
public void setFirstName(String firstName) {
this.firstName = firstName;
}
// setters for all fields
public String toString() {
return String.format("[%s,%s,%s]",firstName,lastName,address,city,country,date);
}
}
Now, if you read the data and have a resultset, you will create a new customer object and set the fields:
List<Customer> customers = new ArrayList<Customer>();
ResultSet rs = stmt.executeQuery("SELECT * from CUSTOMER;");
while (rs.next()) {
Customer customer = new Customer();
customer.setFirstName(rs.get("First_Name"));
// ... and so on
customers.add(customer);
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
