Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ResultSet how to put it into a ArrayList

Is "ResultSet" considered to be an ArrayList? I'm talking about jdbc. If no, then how do I put the information i get from my DB using the

while (result.next()) {
....

}

syntax into an ArrayList called something like hotelResult?

I hope it was understandable.

like image 654
Adem Ökmen Avatar asked Sep 30 '14 18:09

Adem Ökmen


2 Answers

A ResultSet is not an ArrayList. Rather, it is a special object (Interface) to hold data retrieved by queries via JDBC connections.

A ResultSet object cannot be updated, and can only be traversed forward... not back. By default, you can only iterate through it once, from the first row to the last (though with a bit of coding, you can generate a ResultSet object that can be edited and traversed bi-directionally).

The records stored within a ResultSet object can easily be placed within an ArrayList. Here is an example on how you can do this:

Connection con = ... ;
Statement stmt = ... ;
ResultSet results = stmt.executeQuery("..."); 

//Stores properties of a ResultSet object, including column count
ResultSetMetaData rsmd = results.getMetaData(); 
int columnCount = rsmd.getColumnCount();

ArrayList<String> hotelResultList = new ArrayList<>(columnCount); 
while (results.next()) {              
   int i = 1;
   while(i <= columnCount) {
        hotelResultList.add(results.getString(i++));
   }
}

NOTE: This example assumes a single String being returned in the query, such as a Hotel name. You will likely want to hold multiple pieces of data about each hotel, in which case you would create a "Hotel" object, and then create the ArrayList as a List of Hotel objects. By using a rowmapper, each hotel object can be populated with the associated data.

In addition, using one of the popular JDBC frameworks to handle JDBC connections, queries, and result sets can simplify the process further.

like image 158
Michael M Avatar answered Sep 28 '22 12:09

Michael M


I will help u out :)! Create the needed variables in the class see my example :)

public class HotelData {
    private String hotelName = null;
    private int hotelTelephone = 0;

    public HotelData(String hotelName, int hotelTelephone) {
    this.hotelName = hotelName;
    this.hotelTelephone = hotelTelephone;
    }
}

Now create the ArrayList:

public ArrayList<HotelData> hotelResult = new ArrayList<HotelData>();

With the while method now:

while(result.next()) {
    hotelResult.add(new HotelData(result.getString("Enter columnname"), result.getInt("Enter colummname")));
}

Hope this will help u buddy :)! If u need to get the data from the ArrayList u can simply write ur own get methods in the HotelData class!

like image 37
Bart1612 Avatar answered Sep 28 '22 13:09

Bart1612