使用JDBC語句進行批次插入


將一組INSERT語句組合在一起並一次執行它們被稱為批次插入。

使用Statement物件進行批次插入

要使用Statement物件執行一批插入語句:

  • 將語句新增到批處理中 - 一個一個地準備INSERT查詢,並使用Statement介面的addBatch()方法將它們新增到批處理中,如下所示:
String insert1 = Insert into table_name values(value1, value2, value3, ......);
stmt.addBatch(insert1);
String insert2 = Insert into table_name values(value1, value2, value3, ......);
stmt.addBatch(insert2);
String insert3 = Insert into table_name values(value1, value2, value3, ......);
stmt.addBatch(insert3);
  • 執行批處理 - 新增所需語句後,需要使用Statement介面的executeBatch()方法執行批處理。
stmt.executeBatch();

使用批次插入,我們可以減少通訊開銷並提高Java應用程式的效能。

注意 - 在將語句新增到批處理之前,需要使用con.setAutoCommit(false)關閉自動提交,並在執行批處理後,需要使用con.commit()方法儲存更改。

示例

讓我們使用CREATE語句在MySQL資料庫中建立一個名為Dispatches的表,如下所示:

CREATE table Dispatches (
   Product_Name, varchar(255)
   Name_Of_Customer, varchar(255)
   Month_Of_Dispatch, varchar(255)
   Price, int(11)
   Location, varchar(255)
);

下面的JDBC程式嘗試使用Statement物件一次性執行一堆INSERT語句作為批處理。

示例

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class BatchUpdates {
   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 VALUES ('KeyBoard', 'Amith', 'January', 1000, 'Hyderabad')";
      String insert2 = "INSERT INTO Dispatches VALUES ('Earphones', 'SUMITH', 'March', 500, 'Vishakhapatnam')";
      String insert3 = "INSERT INTO Dispatches VALUES ('Mouse', 'Sudha', 'September', 200, 'Vijayawada')";
      //Adding the statements to 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......

如果驗證表的內容,您可以找到新插入的記錄,如下所示:

+--------------+------------------+-------------------+-------+----------------+
| Product_Name | Name_Of_Customer | Month_Of_Dispatch | Price | Location       |
+--------------+------------------+-------------------+-------+----------------+
| KeyBoard     | Amith            | January           | 1000  | Hyderabad      |
| Earphones    | SUMITH           | March             | 500   | Vishakhapatnam |
| Mouse        | Sudha            | September         | 200   | Vijayawada     | 
+--------------+------------------+-------------------+-------+----------------+

更新於:2019年7月30日

313 次瀏覽

啟動您的職業生涯

完成課程後獲得認證

開始
廣告