Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Phương thức setAutoCommit() trong JDBC có tác dụng gì?


Khi commit database, nó lưu tất cả thay đổi đã thực hiện đến thời điểm đó.

Bạn có thể commit database bằng phương thức commit(). Khi có vấn đề, bạn có thể revert database về điểm này bằng rollback(). Mặc định một số database tự động commit. Nhưng khi quản lý transaction, bạn cần commit thủ công.

Trong tình huống này, dùng phương thức setAutoCommit(). Phương thức thuộc interface Connection, chấp nhận giá trị boolean.

Nếu truyền true: bật auto-commit. Nếu truyền false: tắt auto-commit.

Tắt auto-commit:

con.setAutoCommit(false);

Ví dụ

Chương trình chèn dữ liệu vào bảng dùng batch processing. Set auto-commit false, thêm statement vào batch, thực thi batch, rồi commit thủ công:

import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.Statement; 

public class BatchProcessing_Statement { 
    public static void main(String args[]) throws Exception { 
        // Lấy kết nối 
        String mysqlUrl = "jdbc:mysql://localhost/sampleDB"; 
        Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); 
        System.out.println("Kết nối thành công......"); 
        // CREATE TABLE Dispatches( Product_Name VARCHAR(255), Name_Of_Customer VARCHAR(255), Month_Of_Dispatch VARCHAR(255), Price INT, Location VARCHAR(255)); 
        // Tạo Statement object 
        Statement stmt = con.createStatement(); 
        // Tắt auto-commit 
        con.setAutoCommit(false); 
        // Câu lệnh chèn bản ghi 
        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')"; 
        // Thêm statement vào batch 
        stmt.addBatch(insert1); 
        stmt.addBatch(insert2); 
        stmt.addBatch(insert3); 
        // Thực thi batch 
        stmt.executeBatch(); 
        // Lưu thay đổi 
        con.commit(); 
        System.out.println("Bản ghi đã chèn......"); 
    } 
}

Kết quả

Kết nối thành công...... 
Bản ghi đã chèn......