手动将数据添加到Java ResultSet

时间:2012-03-23 09:46:35

标签: java jdbc resultset

我不确定这可能是一个相当愚蠢的问题。但是可以手动将数据/值添加到java结果集中吗?例如,如果我已经有一个现有的填充ResultSet,有没有办法在它上面添加更多数据?

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

谢谢!

3 个答案:

答案 0 :(得分:4)

您可以使用自定义实现包装任何JDBC ResultSet

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() { ... }
}

您的自定义结果集的行为与任何其他结果集相同。从您的自定义结果集中读取数据的客户端代码将忽略您在“引擎盖下”对其执行的更改。换句话说,您可以假装某些数据可用

public class MyResultSet implements ResultSet {
  // [...]

  @Override
  public int getInt(int index) throws SQLException {
    if (index == 3) {
      return 42;
    } else {
      return delegate.getInt(index);
    }
  }
}

答案 1 :(得分:3)

您可以向ResultSet using insertRow()添加值,但这也会将数据添加到基础数据库。如果你想这样做,你会做类似的事情:

rs.moveToInsertRow();
rs.updateString("someColumn", "someValue");
rs.insertRow();

如果您只是想在不修改数据库的情况下将数据添加到结果中,请将ResultSet中的数据添加到ListSet或类似的内容并修改它。

答案 2 :(得分:0)

您需要创建一个将返回可更新ResultSet的语句。例如:

  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