데이터베이스를 커밋하면 특정 시점까지 수행된 모든 변경 사항이 저장됩니다.
commit()을 사용하여 데이터베이스를 커밋할 수 있습니다. 방법. 문제가 발생할 때마다 rollback()을 사용하여 데이터베이스를 이 지점으로 되돌릴 수 있습니다. 방법. 기본적으로 일부 데이터베이스는 데이터베이스를 자동으로 커밋합니다. 그러나 트랜잭션을 관리하는 동안 데이터베이스를 수동으로 커밋해야 합니다.
이 시나리오에서는 setAutoCommit() 메서드를 사용할 수 있습니다. 이 메소드는 Connection 인터페이스에 속하며 부울 값을 받습니다.
이 메서드에 true를 전달하면 데이터베이스의 자동 커밋 기능이 켜지고, 이 메서드에 false를 전달하면 데이터베이스의 자동 커밋 기능이 꺼집니다.
다음과 같이 이 방법을 사용하여 데이터베이스의 자동 커밋 기능을 켤 수 있습니다.
Con.setAutoCommit(false);
예시
다음 프로그램은 일괄 처리를 사용하여 이 테이블에 데이터를 삽입합니다. 여기에서 자동 커밋을 false로 설정하고 필요한 명령문을 배치에 추가하고 배치를 실행한 다음 자체적으로 데이터베이스를 커밋합니다.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class BatchProcessing_Statement {
public static void main(String args[])throws Exception {
//Getting the connection
String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
//CREATE TABLE Dispatches( Product_Name VARCHAR(255), Name_Of_Customer
VARCHAR(255), Month_Of_Dispatch VARCHAR(255), Price INT, Location VARCHAR(255));
//Creating a Statement object
Statement stmt = con.createStatement();
//Setting auto-commit false
con.setAutoCommit(false);
//Statements to insert records
String insert1 = "INSERT INTO Dispatches( Product_Name , Name_Of_Customer , "
+ "Month_Of_Dispatch , Price, Location) VALUES "
+ "('KeyBoard', 'Amith', 'January', 1000, 'hyderabad')";
String insert2 = "INSERT INTO Dispatches( Product_Name , Name_Of_Customer , "
+ "Month_Of_Dispatch , Price, Location) VALUES "
+ "('Earphones', 'SUMITH', 'March', 500, 'Vishakhapatnam')";
String insert3 = "INSERT INTO Dispatches( Product_Name , Name_Of_Customer , "
+ "Month_Of_Dispatch , Price, Location) VALUES "
+ "('Mouse', 'Sudha', 'September', 200, 'Vijayawada')";
//Adding the statements to the batch
stmt.addBatch(insert1);
stmt.addBatch(insert2);
stmt.addBatch(insert3);
//Executing the batch
stmt.executeBatch();
//Saving the changes
con.commit();
System.out.println("Records inserted......");
}
} 출력
Connection established...... Records inserted......