Statement batch update

本文介绍了如何在Java JDBC中通过关闭自动提交功能来实现数据库的批量更新操作,并使用事务确保数据的一致性和完整性。文中提供了具体的代码示例,展示了如何创建Statement对象、添加SQL语句到批处理中并执行批处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

To perform a Statement batch update, you must turn off auto-commit. In Java(TM) Database Connectivity (JDBC), auto-commit is on by default. Auto-commit means any updates to the database are committed after each SQL statement is processed. If you want to treat a group of statements being handed to the database as one functional group, you do not want the database committing each statement individually. If you do not turn off auto-commit and a statement in the middle of the batch fails, you cannot roll back the entire batch and try it again because half of the statements have been made final. Further, the additional work of committing each statement in a batch creates a lot of overhead. See Transactions for more details.

After turning off auto-commit, you can create a standard Statement object. Instead of processing statements with methods such as executeUpdate, you add them to the batch with the addBatch method. Once you have added all the statements you want to the batch, you can process all of them with the executeBatch method. You can empty the batch at anytime with the clearBatch method.

The following example shows how you can use these methods:

Example: Statement batch update

Note: Read the Code example disclaimer for important legal information.


ContractedBlock.gif ExpandedBlockStart.gif Code
1connection.setAutoCommit(false);
2Statement statement = connection.createStatement();
3statement.addBatch("INSERT INTO TABLEX VALUES(1, 'Cujo')");
4statement.addBatch("INSERT INTO TABLEX VALUES(2, 'Fred')");
5statement.addBatch("INSERT INTO TABLEX VALUES(3, 'Mark')");
6int [] counts = statement.executeBatch();
7connection.commit();

 

In this example, an array of integers is returned from the executeBatch method. This array has one integer value for each statement that is processed in the batch. If values are being inserted into the database, the value for each statement is 1 (that is, assuming successful processing). However, some of the statements may be update statements that affect multiple rows. If you put any statements in the batch other than INSERT, UPDATE, or DELETE, an exception occurs.

   backtrack:https://publib.boulder.ibm.com/infocenter/iseries/v5r3/index.jsp?topic=/rzaha/batchstm.htm

转载于:https://www.cnblogs.com/jcleung/archive/2009/04/30/1446906.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值