Java & MySQL - 批處理



批處理允許您將相關的SQL語句分組到一個批處理中,並透過一次呼叫提交到資料庫。

當您一次向資料庫傳送多個SQL語句時,您可以減少通訊開銷,從而提高效能。

  • JDBC驅動程式不需要支援此功能。您應該使用DatabaseMetaData.supportsBatchUpdates()方法來確定目標資料庫是否支援批更新處理。如果您的JDBC驅動程式支援此功能,則該方法返回true。

  • Statement、PreparedStatementCallableStatementaddBatch()方法用於將單個語句新增到批處理中。executeBatch()用於啟動對所有分組語句的執行。

  • executeBatch()返回一個整數陣列,陣列的每個元素代表相應更新語句的更新計數。

  • 就像您可以將語句新增到批處理以進行處理一樣,您也可以使用clearBatch()方法將其刪除。此方法刪除您使用addBatch()方法新增的所有語句。但是,您不能選擇性地選擇要刪除哪個語句。

使用Statement物件的批處理

以下是使用Statement物件進行批處理的典型步驟序列:

  • 使用createStatement()方法建立一個Statement物件。

  • 使用setAutoCommit()將自動提交設定為false。

  • 使用在建立的Statement物件上的addBatch()方法將任意數量的SQL語句新增到批處理中。

  • 使用在建立的Statement物件上的executeBatch()方法執行所有SQL語句。

  • 最後,使用commit()方法提交所有更改。

示例

以下程式碼片段提供了一個使用Statement物件進行批次更新的示例:

// Create statement object
Statement stmt = conn.createStatement();

// Set auto-commit to false
conn.setAutoCommit(false);

// Create SQL statement
String SQL = "INSERT INTO Employees (id, first, last, age) " +
             "VALUES(200,'Zia', 'Ali', 30)";
// Add above SQL statement in the batch.
stmt.addBatch(SQL);

// Create one more SQL statement
String SQL = "INSERT INTO Employees (id, first, last, age) " +
             "VALUES(201,'Raj', 'Kumar', 35)";
// Add above SQL statement in the batch.
stmt.addBatch(SQL);

// Create one more SQL statement
String SQL = "UPDATE Employees SET age = 35 " +
             "WHERE id = 100";
// Add above SQL statement in the batch.
stmt.addBatch(SQL);

// Create an int[] to hold returned values
int[] count = stmt.executeBatch();

//Explicitly commit statements to apply changes
conn.commit();

使用PrepareStatement物件的批處理

以下是使用PrepareStatement物件進行批處理的典型步驟序列:

  • 建立帶有佔位符的SQL語句。

  • 使用prepareStatement()方法建立PrepareStatement物件。

  • 使用setAutoCommit()將自動提交設定為false。

  • 使用在建立的Statement物件上的addBatch()方法將任意數量的SQL語句新增到批處理中。

  • 使用在建立的Statement物件上的executeBatch()方法執行所有SQL語句。

  • 最後,使用commit()方法提交所有更改。

以下程式碼片段提供了一個使用PrepareStatement物件進行批次更新的示例:

// Create SQL statement
String SQL = "INSERT INTO Employees (id, first, last, age) " +
             "VALUES(?, ?, ?, ?)";

// Create PrepareStatement object
PreparedStatemen pstmt = conn.prepareStatement(SQL);

//Set auto-commit to false
conn.setAutoCommit(false);

// Set the variables
pstmt.setInt( 1, 400 );
pstmt.setString( 2, "Pappu" );
pstmt.setString( 3, "Singh" );
pstmt.setInt( 4, 33 );
// Add it to the batch
pstmt.addBatch();

// Set the variables
pstmt.setInt( 1, 401 );
pstmt.setString( 2, "Pawan" );
pstmt.setString( 3, "Singh" );
pstmt.setInt( 4, 31 );
// Add it to the batch
pstmt.addBatch();

//add more batches
.
.
.
.
//Create an int[] to hold returned values
int[] count = stmt.executeBatch();

//Explicitly commit statements to apply changes
conn.commit();
廣告
© . All rights reserved.