Search code examples
javajdbcresultset

Manually add data to a Java ResultSet


I'm not sure if this might be a rather stupid question. But is it possible to manually add data/values into a java resultset? For instance if I already have an existing populated ResultSet, is there a way to add more data ontop of it?

//if this was possible for instance
ResultSet rs;
rs.setData("someValue");

Thanks!


Solution

  • You can wrap any JDBC ResultSet with your custom implementation:

    public class MyResultSet implements ResultSet {
    
      // Delegate most implementations to the underlying database result set:
      private final ResultSet delegate;
      public MyResultSet(ResultSet delegate) {
        this.delegate = delegate;
      }
    
      @Override
      public int getInt(int index) throws SQLException {
        return delegate.getInt(index);
      }
    
      // [... more delegate methods ...]
    
      // Add custom methods
      public void setData(Object someValue) { ... }
      public Object getData() { ... }
    }
    

    Your custom result set behaves like any other result set. Client code reading data from your custom result set will be oblivious of the changes you perform to it "under the hood". In other words, you can pretend that some data is available

    public class MyResultSet implements ResultSet {
      // [...]
    
      @Override
      public int getInt(int index) throws SQLException {
        if (index == 3) {
          return 42;
        } else {
          return delegate.getInt(index);
        }
      }
    }