chrisg
chrisg

Reputation: 41655

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.

Upvotes: 1

Views: 13726

Answers (4)

FBB
FBB

Reputation: 1465

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.

Upvotes: 0

Bozho
Bozho

Reputation: 597036

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.

Upvotes: 3

Buhake Sindi
Buhake Sindi

Reputation: 89169

I don't know exactly what you want to achieve, but can I introduce you to the DAO (Data Access Object) Pattern?

Upvotes: 0

jzd
jzd

Reputation: 23629

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.

Upvotes: 2

Related Questions