2012-03-23 1 views
1

이것이 다소 어리석은 질문 일 수 있는지 확실하지 않습니다. 하지만 수동으로 데이터/값을 Java 결과 집합에 추가 할 수 있습니까? 예를 들어, 이미 채워진 ResultSet이 이미 있다면, 거기에 더 많은 데이터를 추가 할 수있는 방법이 있습니까?수동으로 Java ResultSet에 데이터 추가

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

고마워요!

답변

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

귀하의 사용자 정의 결과 세트는 다른 결과 집합처럼 동작합니다. 사용자 정의 결과 집합의 데이터를 읽는 클라이언트 코드는 "후드"에서 수행 한 변경 사항을 알지 못합니다. 즉, 일부 데이터 당신은 ResultSet 갱신을 반환하는 문을 작성해야

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

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

ResultSetusing insertRow()에도 에 값을 추가 할 수 있습니다. 기본 데이터베이스에도 데이터가 추가됩니다. 이 작업을 수행하고 싶다면 당신은 뭔가를 할 거라고 :

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

그냥 데이터베이스에 ResultSet에서 데이터를 추가 List 또는 Set 또는 비슷한 수정 수정하지 않고 결과에 데이터를 추가하려면 그.

0

사용할 수 있는지 척 할 수 있습니다. 예 :

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