简体   繁体   中英

Parse a Database Result Set into an Object List

I am trying to get all data from a table contained in a database, and parse it into a List. I have tried a few different techniques and can't get it working. I am trying to serialize the ResultSet so I can send it over a socket. The code I have got so far is:

public Object readJavaObject(String query, Connection con) throws Exception
{        
    PreparedStatement stmt = con.prepareStatement(query);
    //stmt.setString(1, id);
    query_results = stmt.executeQuery();
    while (query_results.next())
    {
        dataObject = query_results.getObject(1);
    }
    query_results.close();
    stmt.close();

    return dataObject;
}

public void run()
{
    try
    {
        Class.forName(dbClass);
        con = DriverManager.getConnection (dbUrl, user, pass);
        query = "SELECT * FROM Bench_table";
        dataList = (List) this.readJavaObject(query, con);
        con.close();
    }
}

I'm not sure what code to write around readJavaObject . Can anyone help to point out where the issue is?

Thanks for any help.

Take a look at DbUtils (from apache-commons).

If you need a more complex solution for mapping sql results to java objects, take a look at object-relational mapping . In Java the standard is JPA (Java Persistence API), with Hibernate, EclipseLink and OpenJPA as the most famous implementors.

There are several issues with your code.

  1. You loop through the results but only return data from the last row. Instead create a List in the readJavaObject method and add an element each pass through the loop.
  2. Instead of getting the item in the first column, I assume you want all the data. You are going to have to be more specific with which "get" methods you use to pull data off the ResultSet. Possibly create a POJO to represent a row of data, then inside the loop populate it and store it in the list.
  3. Assuming you use a POJO, you might want to use generics with your list to make it easier to get items out of it without having to cast.

I recently discovered the CachedRowSet , which does exactly what OP needs. It notably allows to serialize a ResultSet , and to restore the original when needed.

我不确定您要实现的目标,但是我可以向您介绍DAO(数据访问对象)模式吗?

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