如果您提交數據庫,它將保存到該特定點之前所做的所有更改。
您可以使用 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() 方法有什么用?的詳細內容,更多請關注www.92cms.cn其它相關文章!






