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!
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);
}
}
}
You can add values to a ResultSet
using insertRow()
but this will also add the data to the underlying database. If you wanted to do this you'd do something like:
rs.moveToInsertRow();
rs.updateString("someColumn", "someValue");
rs.insertRow();
If you just want to add data to the results without modifying the database add the data from the ResultSet
to a List
or Set
or something similar and modify that.
You need to create a statement that will return updatable ResultSet
. Example:
Statement stmt = connection.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE
);
ResultSet resultSet = stmt.executeQuery(" SELECT col1 FROM tablename ");
rs.absolute(5); // moves the cursor to the 5th row of rs
rs.updateString("col1", "NEW VALUE"); // updates the col1 column of row 5 to be NEW VALUE
rs.updateRow(); // updates the row in the data source