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


在数据库中执行一个批处理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 代码

try {    
    // Disable auto-commit    
    connection.setAutoCommit(false);    
   
    // Create a prepared statement    
    String sql = "INSERT INTO my_table VALUES(?)";    
    PreparedStatement pstmt = connection.prepareStatement(sql);    
   
    // Insert 10 rows of data    
    for (int i=0; i<10; i++) {    
        pstmt.setString(1, ""+i);    
        pstmt.addBatch();    
    }    
   
    // Execute the batch    
    int [] updateCounts = pstmt.executeBatch();    
   
    // All statements were successfully executed.    
    // updateCounts contains one element for each batched statement.    
    // updateCounts[i] contains the number of rows affected by that statement.    
    processUpdateCounts(updateCounts);    
   
    // Since there were no errors, commit    
    connection.commit();    
} catch (BatchUpdateException e) {    
    // Not all of the statements were successfully executed    
    int[] updateCounts = e.getUpdateCounts();    
   
    // Some databases will continue to execute after one fails.    
    // If so, updateCounts.length will equal the number of batched statements.    
    // If not, updateCounts.length will equal the number of successfully executed statements    
    processUpdateCounts(updateCounts);    
   
    // Either commit the successfully executed statements or rollback the entire batch    
    connection.rollback();    
} catch (SQLException e) {    
}    
   
public static void processUpdateCounts(int[] updateCounts) {    
    for (int i=0; i<updateCounts.length; i++) {    
        if (updateCounts[i] >= 0) {    
            // Successfully executed; the number represents number of affected rows    
        } else if (updateCounts[i] == Statement.SUCCESS_NO_INFO) {    
            // Successfully executed; number of affected rows not available    
        } else if (updateCounts[i] == Statement.EXECUTE_FAILED) {    
            // Failed to execute    
        }    
    }    
}   

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值