Java – Copy ResultSet without using CachedRowSetImpl.execute().

Copy ResultSet without using CachedRowSetImpl.execute()…. here is a solution to the problem.

Copy ResultSet without using CachedRowSetImpl.execute().

I’m trying to close the connection after executing a query. Previously, I just created a CachedRowSetImpl instance that would take care of freeing up resources for me. However, I’m using the Hive database driver for my Hadoop project. It does not support CachedRowSetImpl.execute(). I wonder if there is any other way for me to copy the ResultSet object and close the connection?

Solution

You can populate CachedRowSet: from an existing ResultSet

public static RowSet executeQuery(String sql) throws Exception {
    Connection con = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    try{
        con = openConnection();
        ps = con.prepareStatement(sql);
        rs = ps.executeQuery();
        CachedRowSet rows = new CachedRowSetImpl();
        rows.populate(rs);
        return rows;
    }finally{
        rs.close();
        ps.close();
        con.close();            
    }       
}

Related Problems and Solutions