`
Eric_liu
  • 浏览: 89666 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

在数据库中执行一个批处理SQL语句(zhuan)

阅读更多

在数据库中执行一个批处理SQL语句
With batch updating, a set of SQL statements is assembled and then sent altogether to the database for execution. Batch updating can improve performance.
This example creates a batch of insert statements. Auto-commit is disabled so that you have the choice of committing or not in the event of an exception.

java 代码
  1. try {   
  2.     // Disable auto-commit   
  3.     connection.setAutoCommit(false);   
  4.   
  5.     // Create a prepared statement   
  6.     String sql = "INSERT INTO my_table VALUES(?)";   
  7.     PreparedStatement pstmt = connection.prepareStatement(sql);   
  8.   
  9.     // Insert 10 rows of data   
  10.     for (int i=0; i<10; i++) {   
  11.         pstmt.setString(1""+i);   
  12.         pstmt.addBatch();   
  13.     }   
  14.   
  15.     // Execute the batch   
  16.     int [] updateCounts = pstmt.executeBatch();   
  17.   
  18.     // All statements were successfully executed.   
  19.     // updateCounts contains one element for each batched statement.   
  20.     // updateCounts[i] contains the number of rows affected by that statement.   
  21.     processUpdateCounts(updateCounts);   
  22.   
  23.     // Since there were no errors, commit   
  24.     connection.commit();   
  25. catch (BatchUpdateException e) {   
  26.     // Not all of the statements were successfully executed   
  27.     int[] updateCounts = e.getUpdateCounts();   
  28.   
  29.     // Some databases will continue to execute after one fails.   
  30.     // If so, updateCounts.length will equal the number of batched statements.   
  31.     // If not, updateCounts.length will equal the number of successfully executed statements   
  32.     processUpdateCounts(updateCounts);   
  33.   
  34.     // Either commit the successfully executed statements or rollback the entire batch   
  35.     connection.rollback();   
  36. catch (SQLException e) {   
  37. }   
  38.   
  39. public static void processUpdateCounts(int[] updateCounts) {   
  40.     for (int i=0; i<updateCounts.length; i++) {   
  41.         if (updateCounts[i] >= 0) {   
  42.             // Successfully executed; the number represents number of affected rows   
  43.         } else if (updateCounts[i] == Statement.SUCCESS_NO_INFO) {   
  44.             // Successfully executed; number of affected rows not available   
  45.         } else if (updateCounts[i] == Statement.EXECUTE_FAILED) {   
  46.             // Failed to execute   
  47.         }   
  48.     }   
  49. }   
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics