>  기사  >  데이터 베이스  >  JDBC에서 setAutoCommit() 메소드의 용도는 무엇입니까?

JDBC에서 setAutoCommit() 메소드의 용도는 무엇입니까?

WBOY
WBOY앞으로
2023-08-28 15:21:021291검색

JDBC 中 setAutoCommit() 方法有什么用?

데이터베이스에 커밋하면 해당 특정 지점까지의 모든 변경 사항이 저장됩니다.

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......

위 내용은 JDBC에서 setAutoCommit() 메소드의 용도는 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 tutorialspoint.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제