首頁  >  文章  >  資料庫  >  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刪除