JDBC에서 ResultSet의 내용을 직접 수정하려면, Statement 객체를 생성할 때 결과 집합을 업데이트 가능(updatable) 타입으로 지정해야 합니다. 아래와 같이 createStatement() 메서드에 스크롤 타입과 동시성 모드를 인자로 전달하면 됩니다.
// Statement 객체 생성 Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
updateXXX() 메서드 이해하기
ResultSet 인터페이스는 데이터를 읽어오는 getXXX() 메서드뿐만 아니라, 현재 행(row)의 내용을 수정할 수 있는 updateXXX() 메서드도 제공합니다. 예를 들어 updateInt(), updateString() 등이 있으며, 각 데이터 타입에 맞는 메서드를 사용하면 됩니다.
이 메서드들은 두 가지 방식으로 대상 열을 지정할 수 있습니다.
- 정수(int): 열의 인덱스 번호 (1부터 시작)
- 문자열(String): 열의 이름(레이블)
수정 작업 후에는 반드시 updateRow()를 호출해야 변경 사항이 실제 데이터베이스에 반영됩니다.
주의: ResultSet의 내용을 업데이트하려면 해당 테이블에 기본 키(primary key)가 존재해야 합니다. 기본 키가 없으면 JDBC 드라이버가 어떤 행을 수정해야 할지 식별할 수 없어 업데이트가 실패합니다.
예제: Employees 테이블
다음과 같이 5개의 레코드를 가진 Employees 테이블이 있다고 가정해 보겠습니다.
+----+---------+--------+----------------+ | Id | Name | Salary | Location | +----+---------+--------+----------------+ | 1 | Amit | 3000 | Hyderabad | | 2 | Kalyan | 4000 | Vishakhapatnam | | 3 | Renuka | 6000 | Delhi | | 4 | Archana | 9000 | Mumbai | | 5 | Sumith | 11000 | Hyderabad | +----+---------+--------+----------------+
아래 예제는 ResultSet을 통해 모든 직원의 급여를 5000씩 인상한 뒤, 특정 레코드를 삭제하는 과정을 보여줍니다.
import java.sql.*;
public class ResultSetExample {
public static void main(String[] args) throws Exception {
// 드라이버 등록
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
// 연결 생성
String mysqlUrl = "jdbc:mysql://localhost/TestDB";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
// 업데이트 가능한 Statement 객체 생성
Statement stmt = con.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
// 데이터 조회
ResultSet rs = stmt.executeQuery("select * from Employees");
// 테이블 내용 출력
System.out.println("Contents of the table: ");
printRs(rs);
// 커서를 ResultSet 시작 위치로 이동
rs.beforeFirst();
// 모든 직원의 급여를 5000씩 인상
while(rs.next()){
// 열 이름으로 값 조회
int newSal = rs.getInt("Salary") + 5000;
rs.updateInt( "Salary", newSal );
rs.updateRow();
}
System.out.println("Contents of the ResultSet after increasing salaries");
printRs(rs);
// 두 번째 레코드로 커서 이동
rs.beforeFirst();
rs.absolute(2);
System.out.println("Record we need to delete: ");
System.out.print("ID: " + rs.getInt("id"));
System.out.print(", Salary: " + rs.getInt("Salary"));
System.out.print(", Name: " + rs.getString("Name"));
System.out.println(", Location: " + rs.getString("Location"));
System.out.println(" ");
// 현재 행 삭제
rs.deleteRow();
System.out.println("Contents of the ResultSet after deleting one records...");
printRs(rs);
System.out.println("Goodbye!");
}
public static void printRs(ResultSet rs) throws SQLException{
// 첫 번째 행부터 시작하도록 보장
rs.beforeFirst();
while(rs.next()){
System.out.print("ID: " + rs.getInt("id"));
System.out.print(", Salary: " + rs.getInt("Salary"));
System.out.print(", Name: " + rs.getString("Name"));
System.out.println(", Location: " + rs.getString("Location"));
}
System.out.println();
}
}실행 결과
위 프로그램을 실행하면 다음과 같은 출력을 확인할 수 있습니다. 급여가 5000씩 증가했고, ID 2번(Kalyan) 레코드가 삭제된 것을 볼 수 있습니다.
Connection established...... Contents of the table: ID: 1, Salary: 3000, Name: Amit, Location: Hyderabad ID: 2, Salary: 4000, Name: Kalyan, Location: Vishakhapatnam ID: 3, Salary: 6000, Name: Renuka, Location: Delhi ID: 4, Salary: 9000, Name: Archana, Location: Mumbai ID: 5, Salary: 11000, Name: Sumith, Location: Hyderabad Contents of the resultset after increaing salaries ID: 1, Salary: 8000, Name: Amit, Location: Hyderabad ID: 2, Salary: 9000, Name: Kalyan, Location: Vishakhapatnam ID: 3, Salary: 11000, Name: Renuka, Location: Delhi ID: 4, Salary: 14000, Name: Archana, Location: Mumbai ID: 5, Salary: 16000, Name: Sumith, Location: Hyderabad Record we need to delete: ID: 2, Salary: 9000, Name: Kalyan, Location: Vishakhapatnam Contents of the resultset after deleting one records... ID: 1, Salary: 8000, Name: Amit, Location: Hyderabad ID: 3, Salary: 11000, Name: Renuka, Location: Delhi ID: 4, Salary: 14000, Name: Archana, Location: Mumbai ID: 5, Salary: 16000, Name: Sumith, Location: Hyderabad Goodbye!
핵심 정리
- ResultSet을 업데이트하려면
CONCUR_UPDATABLE동시성 모드로 Statement를 생성해야 합니다. updateXXX()로 값을 변경한 후에는 반드시updateRow()를 호출해야 데이터베이스에 반영됩니다.deleteRow()를 사용하면 현재 커서가 가리키는 행을 삭제할 수 있습니다.- 업데이트 가능한 ResultSet을 사용하려면 테이블에 기본 키가 필요합니다.