對這文章發表回應
發表限制: 非會員 可以發表
JDBC批量處理
批處理允許將相關的SQL語句組合成一個批處理和一個調用數據庫提交。
當一次發送多個SQL語句到數據庫,可以減少通信開銷的數額,從而提高了性能。
JDBC驅動程序不需要支持此功能。應該使用DatabaseMetaData.supportsBatchUpdates()方法來確定目標數據庫支持批量更新處理。如果你的JDBC驅動程序支持此功能的方法返回true。
聲明addBatch()方法,PreparedStatement和CallableStatement用於各個語句添加到批處理。executeBatch()將用於啟動所有組合在一起的語句的執行。
executeBatch()將返回一個整數數組,數組中的每個元素代表了各自的更新語句的更新計數。
可以添加語句批量處理,可以用theclearBatch()方法刪除它們。此方法刪除所有已添加的addBatch()方法的語句。但是,不能有選擇性地選擇要刪除的語句。
批處理和Statement對象:
下麵是步驟,使用批處理使用說明書對象的典型順序:
使用createStatement()方法創建一個Statement對象。
設置使用自動提交為false,使用 setAutoCommit().
添加任意多個到批量使用addBatch SQL語句(上創建語句對象)的方法。
執行使用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();
為了更好地理解,建議學習研究 JDBC批處理用Statement對象示例代碼.
批處理使用prepareStatement結果對象:
下麵是步驟,使用批處理用prepareStatement結果對象的典型順序:
創建SQL語句的占位符。
使用任一prepareStatement()方法創建prepareStatement結果對象。
設置使用setAutoCommit()自動提交為false。
添加任意多個批量使用addBatch SQL語句(上創建語句對象)的方法。
執行使用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();
為了更好地理解,建議學習研究 實例代碼.
原文出處:JDBC批量處理 - JDBC基礎教程