수색…
소개
명령문 일괄 처리는 여러 개의 명령문을 하나의 단위 (일반
java.sql.Statement
)로 실행하거나 여러 명령문 집합이있는 단일 명령문 ( java.sql.PreparedStatement
) 중 하나입니다.
비고
명령문 일괄 처리는 프로그램이 관련 명령문을 수집하거나 준비된 명령문 관련 매개 변수 값 세트의 경우이를 수집하여 단일 실행으로 데이터베이스 서버로 보냅니다.
명령문 일괄 처리의 이점에는 향상된 성능이 포함될 수 있습니다. 이러한 성능상의 이점이 달성되는 방법은 드라이버 및 데이터베이스 지원에 따라 다르지만 다음이 포함됩니다.
- 모든 명령문 (또는 모든 값 세트)을 하나의 명령으로 전송
- 문장을 하나의 커다란 성명처럼 실행할 수 있도록 다시 작성하기
PreparedStatement를 사용한 일괄 삽입
java.sql.PreparedStatement
사용하여 일괄 처리를 수행하면 해당 매개 변수에 대해 여러 값 세트로 단일 DML 문을 실행할 수 있습니다.
이 예는 insert 문을 준비하고 배치 문에 여러 행을 삽입하는 방법을 보여줍니다.
Connection connection = ...; // obtained earlier
connection.setAutoCommit(false); // disabling autoCommit is recommend for batching
int orderId = ...; // The primary key of inserting and order
List<OrderItem> orderItems = ...; // Order item data
try (PreparedStatement insert = connection.prepareStatement(
"INSERT INTO orderlines(orderid, itemid, quantity) VALUES (?, ?, ?)")) {
// Add the order item data to the batch
for (OrderItem orderItem : orderItems) {
insert.setInt(1, orderId);
insert.setInt(2, orderItem.getItemId());
insert.setInt(3, orderItem.getQuantity());
insert.addBatch();
}
insert.executeBatch();//executing the batch
}
connection.commit();//commit statements to apply changes
Statement를 사용한 일괄 처리 실행
java.sql.Statement
사용하여 일괄 실행하면 여러 DML 문 ( update
, insert
, delete
)을 한 번에 실행할 수 있습니다. 단일 명령문 오브젝트를 작성하고 실행할 명령문을 추가 한 다음 일} 처리를 하나의 명령으로 실행하면됩니다.
Connection connection = ...; // obtained earlier
connection.setAutoCommit(false); // disabling autocommit is recommended for batch execution
try (Statement statement = connection.createStatement()) {
statement.addBatch("INSERT INTO users (id, username) VALUES (2, 'anna')");
statement.addBatch("INSERT INTO userrole(userid, rolename) VALUES (2, 'admin')");
statement.executeBatch();//executing the batch
}
connection.commit();//commit statements to apply changes
노트 :
statement.executeBatch();
반환 된 값을 보유하기 위해 int[]
를 반환 할 것이므로 다음과 같이 배치를 실행할 수 있습니다.
int[] stmExc = statement.executeBatch();//executing the batch
Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow