2011-11-30 2 views
1

"Res_allocation", "ResName"및 다른 "PID"테이블에 두 개의 열이 있습니다. "ResName"에는 단일 "PID"에 대해 여러 값이 있습니다.하나의 값을 기반으로 테이블의 여러 행을 업데이트하는 방법은 무엇입니까?

PID를 기반으로 여러 행에있는 "ResName"값을 업데이트하는 쿼리가 하나 있습니까?

"ResName"의 새 값은 동적으로 제공됩니다. 즉, 사용자 입력입니다. SQL 데이터베이스를 사용합니다.

+0

ResName은 다른 값을 갖습니다. – Vinod

답변

1

이것은 이미 코드에서 수정되었습니다 ... 오류 2 개가있을 수 있지만 핵심은 작동합니다 (코드에서 작동 함). 이상적으로는 Hiberante와 같은 ORM 도구를 사용해야합니다.

기본적으로 배치 업데이트를 설정 한 다음 statement.executeBatch()를 실행하여 실제 업데이트를 수행합니다. 결과가있는 int [] 배열이 반환됩니다. 미리 정의 된 상수 목록과 비교하여 어떤 일이 일어나는지 확인합니다. 이것은 단순히 각 업데이트를 개별적으로 실행하는 것보다 훨씬 빠릅니다. 또한 모든 업데이트를 하나의 트랜잭션으로 결합하여 롤백을 쉽게 수행 할 수 있습니다.

public void updateResNames(List<ResAllocationDTO> list) { 
    String sql = "UPDATE res_allocation SET ResName = ? WHERE PID = ?"; 
    PreparedStatement statement = null; 
    try { 
     statement = connection.prepareStatement(sql); 
     for (ResAllocationDTO dto : list) { 
      statement.setString(1, dto.getResName()); 
      statement.setString(2, dto.getPID()); 
      statement.addBatch(); 
     } 
     int[] result = statement.executeBatch(); 
     for (int i = 0; i < result.length; i++) { 
      if (result[i] == PreparedStatement.EXECUTE_FAILED) { 
       throw new SQLException(String.format("Entry %d failed to execute in the batch insert with a return code of %d.", i, result[i])); 
      } 
     } 
     commit(); 
    } catch (SQLException e) { 
     logger.error(LoggerCodes.DATABASE_ERROR, e); 
     rollback(); 
     throw new RuntimeException(e); 
    } finally { 
     close(statement); 
    } 
} 

은() 커밋 가까운()과 롤백()는 다음과 같습니다 : I 희망

public void close(PreparedStatement statement) { 
    try { 
     if (statement != null && !statement.isClosed()) 
      statement.close(); 
    } catch (SQLException e) { 
     logger.debug(LoggerCodes.TRACE, "Warning! PreparedStatement could not be closed."); 
    } 
} 

protected void commit() { 
    try { 
     if ((connection != null) && !connection.getAutoCommit()) { 
      connection.commit(); 
     } 
    } catch (SQLException e) { 
     logger.debug(LoggerCodes.TRACE, "Warning! ResultSet could not be closed after commit."); 
    } 
} 

protected void rollback() { 
    try { 
     if ((connection != null) && !connection.getAutoCommit()) { 
      connection.rollback(); 
     } 
    } catch (SQLException e) { 
     logger.debug(LoggerCodes.TRACE, "Warning! ResultSet could not be closed after rollback."); 
    } 
} 

이 당신을 도와줍니다

! 행운과 행복을위한 코딩!

+0

이 쿼리는 "ResName"을 모든 행에서 동일하게 업데이트하며 다른 행의 다른 값을 업데이트해야하며이 값은 사용자 선택에서 비롯됩니다. – Vinod

+0

이 경우 일괄 업데이트를 사용합니다. JDBC를 사용하고 있습니까? –

+0

예 ... mysql.jdbc.Driver 일괄 처리 업데이트가 무엇인지 알지 못합니다. 간단한 용어로 답해주세요. – Vinod

관련 문제