简体   繁体   中英

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.

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.

You can use the mybatis. Please use the ORM.

https://en.wikipedia.org/wiki/Object-relational_mapping

You should use OR mapper like Hibernate. Thanks POJO classes you can do whan you want. Some readings:

http://www.tutorialspoint.com/hibernate/hibernate_examples.htm

http://www.mkyong.com/tutorials/hibernate-tutorials/

在代码中的这一行添加括号“()”,使它看起来像这样:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM