Search code examples
javamysqlsqlarraylistresultset

How to get the MySQL query results into a ArrayList<object>


I have SQL query which results in multiple columns. I want to execute this query and get the results into my ArrayList<> instead of the ResultSet. My class for the column definitions is

public class Record{
    private String FileName;
    private String FileID;
    private String Loan;
    private String Page;
}

Query is :

String query = "SELECT FileName, FileID, loanNumnber, PageNumber FROM table";
ResultSet rs = stmt.executeQuery(query);

I want the results of the query in recordData object.

ArrayList<Record> recordData = new ArrayList<Record>;

Please suggest how the arraylist can be populated directly with correct mapping.


Solution

  • Use following code snippet if you want to implement by yourself. It will convert the result set to Record objects and add it to the ArrayList.

    Record record;
    while(rs.next()){
    
         record = new record();
    
         String fileName  = rs.getString("FileName");
         String fileID = rs.getString("FileID");
         String loanNumnber = rs.getString("loanNumnber");
         String pageNumber = rs.getString("PageNumber");
    
        record.setFileName(fileName);
        record.setFileID(fileID);
        record.setLoan(loanNumnber);
        record.setPage(pageNumber);
    
        recordData.add(record)
    }
    
    rs.close();
    

    Otherwise, if you want to use any third party frameworks then there are lot of options such as Hibernate, iBatis etc.