开发者

Parse a Database Result Set into an Object List

开发者 https://www.devze.com 2023-01-26 06:22 出处:网络
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 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 iss开发者_如何学编程ue 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 don't know exactly what you want to achieve, but can I introduce you to the DAO (Data Access Object) Pattern?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号