Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

การใช้งานเมธอด setAutoCommit() ใน JDBC


การ commit บันทึกการเปลี่ยนแปลงทั้งหมดจนถึงจุดนั้น ใช้เมธอด commit() และย้อนกลับได้ด้วย rollback() บางฐานข้อมูล auto-commit โดยอัตโนมัติ แต่จัดการ transaction เองต้องปิด auto-commit

เมธอด setAutoCommit() ของ Connection interface รับค่า boolean:

  • true = เปิด auto-commit
  • false = ปิด auto-commit (จัดการ transaction เอง)
con.setAutoCommit(false);

ตัวอย่าง

โปรแกรม batch processing ปิด auto-commit เพิ่มคำสั่งใน batch รัน batch แล้ว commit เอง:

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

public class BatchProcessing_Statement {
    public static void main(String args[]) throws Exception {
        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));
        Statement stmt = con.createStatement();
        // ปิด auto-commit
        con.setAutoCommit(false);
        // คำสั่ง insert
        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')";
        // เพิ่มใน batch
        stmt.addBatch(insert1);
        stmt.addBatch(insert2);
        stmt.addBatch(insert3);
        // รัน batch
        stmt.executeBatch();
        // commit เอง
        con.commit();
        System.out.println("Records inserted......");
    }
}

ผลลัพธ์

Connection established......
Records inserted......