【问题标题】:Manually add data to a Java ResultSet手动将数据添加到 Java ResultSet
【发布时间】:2012-03-23 09:46:34
【问题描述】:

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

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

谢谢!

【问题讨论】:

    标签: java jdbc resultset


    【解决方案1】:

    您可以使用自定义实现包装任何 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);
        }
      }
    }
    

    【讨论】:

      【解决方案2】:

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

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

      如果您只想在不修改数据库的情况下将数据添加到结果中,请将 ResultSet 中的数据添加到 ListSet 或类似名称并进行修改。

      【讨论】:

        【解决方案3】:

        您需要创建一个返回可更新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
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-10-13
          相关资源
          最近更新 更多