如何在JDBC中啟動事務?


事務是在資料庫上執行的一組工作單元。事務是按邏輯順序完成的工作單元或序列,無論是由使用者手動執行還是由某種資料庫程式自動執行。

事務是對資料庫進行的一個或多個更改的傳播。例如,如果您正在建立記錄、更新記錄或從表中刪除記錄,那麼您就是在對該表執行事務。控制這些事務以確保資料完整性和處理資料庫錯誤非常重要。

結束事務

執行完所需的操作後,可以使用commit命令結束/儲存事務。在JDBC應用程式中,可以使用**Connection**介面的**commit()**方法來實現。

每當事務中出現問題時,您可以使用回滾來撤消對資料庫所做的更改。

啟動事務

通常,在JDBC中,建立連線後,預設情況下,您的連線將處於自動提交模式,即使用此連線執行的每個語句都會自動儲存,這意味著資料庫管理其自身的事務,並且每個單獨的SQL語句都被視為一個事務。

您可以透過關閉自動提交模式來啟用手動事務支援。為此,您需要將布林值false傳遞給**Connection**介面的**setAutoCommit()**方法。

conn.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:///sampleDB";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      //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......

更新於: 2019年7月30日

1K+ 瀏覽量

啟動你的職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.