JDBC 中 setAutoCommit() 方法有什麼作用?
如果提交資料庫,則會儲存到該特定點為止所做的所有更改。
可以使用 **commit()** 方法提交資料庫。出現任何問題時,可以使用 **rollback()** 方法將資料庫回滾到此點。預設情況下,某些資料庫會自動提交資料庫。但是,在管理事務時,需要手動提交資料庫。
在這種情況下,可以使用 setAutoCommit() 方法。此方法屬於 Connection 介面,並接受布林值。
如果向此方法傳遞 true,則會開啟資料庫的自動提交功能;如果向此方法傳遞 false,則會關閉資料庫的自動提交功能。
可以使用此方法關閉資料庫的自動提交功能,如下所示:
Con.setAutoCommit(false);
示例
下面的程式使用批處理處理將資料插入到此表中。在這裡,我們將 auto commit 設定為 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:///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......
廣告