环境:oracle
使用PreparedStatement的executeBatch方法,如果DML操作成功,返回值[-2,-2,...]
an array of update counts containing one element for each command in the batch.

int java.sql.Statement.SUCCESS_NO_INFO = -2 [0xfffffffe]
The constant indicating that a batch statement executed successfully but that no count of the number of rows it affected is available
int java.sql.Statement.EXECUTE_FAILED = -3 [0xfffffffd]
The constant indicating that an error occured while executing a batch statement.

在执行executeBatch()时报错:
(1)使用class12.jar,返回array中的值为[-3,-3,...];
(2)使用ojdbc6.jar,返回array为空数组[]
使用class12.jar或ojdbc6.jar,在遇到出错DML语句前执行的sql都会入库,
即使设定Connection的auto-commit mode为false。
如果期望在执行executeBatch()失败后回退,可以在catch中执行java.sql.Connection.rollback().
使用rollback()需要设置java.sql.Connection.setAutoCommit(false);在操作最后执行提交操作java.sql.Connection.commit();

void rollback()
throws SQLException
Undoes all changes made in the current transaction and releases any database locks currently held by this Connection object. This method should be used only when auto-commit mode has been disabled.
Throws:
SQLException - if a database access error occurs, this method is called while participating in a distributed transaction, this method is called on a closed connection or this Connection object is in auto-commit mode
See Also:
setAutoCommit(boolean)

eg:
java.sql.Connection.setAutoCommit(false);
...
preStmt.addBatch();
....
preStmt.executeBatch();
...
java.sql.Connection.commit();

void java.sql.Connection.setAutoCommit(boolean autoCommit) throws SQLException
Sets this connection's auto-commit mode to the given state. If a connection is in auto-commit mode,
then all its SQL statements will be executed and committed as individual transactions. Otherwise, 
its SQL statements are grouped into transactions that are terminated by a call to either the method commit or the method rollback. 
By default, new connections are in auto-commit mode. 

The commit occurs when the statement completes. The time when the statement completes depends on the type of SQL Statement: 

For DML statements, such as Insert, Update or Delete, and DDL statements, the statement is complete as soon as it has finished executing.
For Select statements, the statement is complete when the associated result set is closed.
For CallableStatement objects or for statements that return multiple results, the statement is complete
when all of the associated result sets have been closed, and all update counts and output parameters have been retrieved.
NOTE: If this method is called during a transaction and the auto-commit mode is changed, the transaction is committed.
If setAutoCommit is called and the auto-commit mode is not changed, the call is a no-op.

Parameters:
autoCommit true to enable auto-commit mode; false to disable it
Throws:
SQLException - if a database access error occurs, setAutoCommit(true) is called while participating in a distributed transaction,
or this method is called on a closed connection
int[] java.sql.Statement.executeBatch() throws SQLException

Submits a batch of commands to the database for execution and if all commands execute successfully, returns an array of update counts. The int elements of the array that is returned are ordered to correspond to the commands in the batch, which are ordered according to the order in which they were added to the batch. The elements in the array returned by the method executeBatch may be one of the following: 

A number greater than or equal to zero -- indicates that the command was processed successfully and is an update count giving the number of rows in the database that were affected by the command's execution
A value of SUCCESS_NO_INFO -- indicates that the command was processed successfully but that the number of rows affected is unknown
If one of the commands in a batch update fails to execute properly, this method throws a BatchUpdateException, and a JDBC driver may or may not continue to process the remaining commands in the batch. However, the driver's behavior must be consistent with a particular DBMS, either always continuing to process commands or never continuing to process commands. If the driver continues processing after a failure, the array returned by the method BatchUpdateException.getUpdateCounts will contain as many elements as there are commands in the batch, and at least one of the elements will be the following: A value of EXECUTE_FAILED -- indicates that the command failed to execute successfully and occurs only if a driver continues to process commands after a command fails
The possible implementations and return values have been modified in the Java 2 SDK, Standard Edition, version 1.3 to accommodate the option of continuing to proccess commands in a batch update after a BatchUpdateException obejct has been thrown. Returns:
an array of update counts containing one element for each command in the batch. The elements of the array are ordered according to the order in which commands were added to the batch.
Throws:
SQLException - if a database access error occurs, this method is called on a closed Statement or the driver does not support batch statements. Throws BatchUpdateException (a subclass of SQLException) if one of the commands sent to the database fails to execute properly or attempts to return a result set.

sql:

-- Create table
create table TB_PERSON
(
id NUMBER(20) not null,
name VARCHAR2(45),
english_name VARCHAR2(45),
age NUMBER(3),
sex VARCHAR2(45),
birthday DATE,
memo VARCHAR2(100),
create_time DATE default sysdate
);
-- Add comments to the table
comment on table TB_PERSON
is '用户信息';
-- Add comments to the columns
comment on column TB_PERSON.id
is 'id';
comment on column TB_PERSON.name
is '姓名';
comment on column TB_PERSON.english_name
is '英文名';
comment on column TB_PERSON.age
is '年龄';
comment on column TB_PERSON.sex
is '性别';
comment on column TB_PERSON.birthday
is '出生日期';
comment on column TB_PERSON.memo
is '备注';
comment on column TB_PERSON.create_time
is '修改时间';
-- Create/Recreate primary, unique and foreign key constraints
alter table TB_PERSON
add primary key (ID)
using index
tablespace USERS
pctfree 10
initrans 2
maxtrans 255;
--drop sequence seq_tb_person_id
create sequence seq_tb_person_id
minvalue 1
maxvalue 999999999
increment by 1 start with 1;
create or replace
trigger trg_tb_person_id before insert on tb_person for each row
begin
select seq_tb_person_id.nextval into :new.id from dual;
end;

http://www.cnblogs.com/xwdreamer/archive/2012/06/08/2542277.html

code:

package sql.batch;

import java.sql.BatchUpdateException;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement; /*2015-7-17*/
public class BatchProcessor {
private String dirver;
private String url;
private String user;
private String password; public BatchProcessor(String dirver, String url, String user, String password) {
super();
this.dirver = dirver;
this.url = url;
this.user = user;
this.password = password;
} public void batch() throws ClassNotFoundException {
System.out.println("Statement.SUCCESS_NO_INFO:" + Statement.SUCCESS_NO_INFO);
System.out.println("Statement.EXECUTE_FAILED:" + Statement.EXECUTE_FAILED); Class.forName(dirver);
Connection conn = null;
PreparedStatement preStmt = null;
try {
conn = DriverManager.getConnection(url, user, password);
preStmt = conn.prepareStatement("truncate table tb_person");
int truncateResult = preStmt.executeUpdate();
System.out.println("Result:" + truncateResult); conn.setAutoCommit(false);
String sql = "insert into tb_person(name,english_name,age,sex,birthday,memo) values(?,?,?,?,?,?)"; preStmt = conn.prepareStatement(sql);
for (int i = 0; i < 5; i++) {
preStmt.setString(1, "Name" + i);
preStmt.setString(2, "English_name" + i); if (i == 3) {
preStmt.setString(3, "test");
} else {
preStmt.setInt(3, 25 + i);
} // preStmt.setInt(3, 25 + i); preStmt.setString(4, (i / 2 == 0 ? "男" : "女"));
preStmt.setDate(5, new Date(System.currentTimeMillis()));
preStmt.setString(6, "memo" + i);
preStmt.addBatch();
} int[] result = preStmt.executeBatch();
conn.commit();
for (int i : result) {
System.out.println("影响的行数" + i);
}
} catch (SQLException e) {
try {
// 如果出错,则此次executeBatch()的所有数据都不入库
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
} // 如果使用ojdbc6.jar,下列代码不需要,因为返回[]
if (e instanceof BatchUpdateException) {
BatchUpdateException bue = (BatchUpdateException) e;
int[] updateCounts = bue.getUpdateCounts();
System.out.println("getUpdateCounts():" + updateCounts.length);
for (int updateCount : updateCounts) {
System.out.println("影响的行数:" + updateCount);
}
}
System.err.println("Error:" + e);
} finally {
if (preStmt != null) {
try {
preStmt.clearBatch();
preStmt.clearParameters();
preStmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
} if (conn != null) {
try {
conn.setAutoCommit(true);
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
} }
}
package sql.batch;

/*2015-7-17*/
public class OracleBatchProcessor extends BatchProcessor { public OracleBatchProcessor() {
// oracle.jdbc.driver.OracleDriver
super("oracle.jdbc.OracleDriver",
"jdbc:oracle:thin:@127.0.0.1:1521:instance1",
"hr",
"password");
} }
package sql.batch;

/*2015-7-17*/
public class Test {
public static void main(String[] args) throws ClassNotFoundException {
OracleBatchProcessor processor = new OracleBatchProcessor();
processor.batch();
} }

全部成功时的输出:

Statement.SUCCESS_NO_INFO:-2
Statement.EXECUTE_FAILED:-3
Result:0
影响的行数-2
影响的行数-2
影响的行数-2
影响的行数-2
影响的行数-2

Tips:
mysql在使用InnoDB引擎时支持事务
http://www.cnblogs.com/zhangjun516/archive/2013/03/19/2968997.html

executeBatch()相关操作汇总的更多相关文章

  1. Object-C中动态类型对象相关操作汇总

    Object-C(以后简称OC)中有id类型,相对于明确定义类型的静态类型,称为动态类型. 使用动态类型,配合多态(不同类型拥有同名方法),动态绑定(运行时决定实际调用的方法)可以将很多判断延迟到运行 ...

  2. Git相关操作汇总

    git clone: 正如上图,当我们打开终端的情况下,默认我们所在的目录是在/home/shiyanlou的,大家可以在终端输入以下命令把目录切换到桌面cd  /home/Desktop这个时候输入 ...

  3. aliyun TableStore相关操作汇总

    总结:这个东西本身可能技术还不成熟,使用的人少,有问题很验证解决 遇到的问题:(1)没有一个GUI工具,使用门槛高(2)查询的GetRange不方便,把查询出来的数据使用System.out.prin ...

  4. Java 常用知识点汇总(数据类型之间转换、字符串的相关操作-截取、转换大小写等)

    1.Java四类八种数据类型 byte:Java中最小的数据类型,在内存中占8位(bit),即1个字节,取值范围-128~127,默认值0 short:短整型,在内存中占16位,即2个字节,取值范围- ...

  5. [转帖]xserver相关知识汇总

    xserver相关知识汇总 https://blog.csdn.net/QTVLC/article/details/81739984   本文主要是从以下几个方面介绍xorg-xserver 相关的知 ...

  6. Spark 1.x 爆内存相关问题汇总及解

    Spark 1.x 爆内存相关问题汇总及解决 OOM # 包括GC Overhead limitjava.lang.OutOfMemoryError # on yarn org.apache.hado ...

  7. solidity的delete操作汇总

    简介 Solidity中的特殊操作符delete用于释放空间,为鼓励主动对空间的回收,释放空间将会返还一些gas. delete操作符可以用于任何变量,将其设置成默认值0. 删除枚举类型时,会将其值重 ...

  8. 从零自学Hadoop(20):HBase数据模型相关操作上

    阅读目录 序 介绍 命名空间 表 系列索引 本文版权归mephisto和博客园共有,欢迎转载,但须保留此段声明,并给出原文链接,谢谢合作. 文章是哥(mephisto)写的,SourceLink 序 ...

  9. 从零自学Hadoop(21):HBase数据模型相关操作下

    阅读目录 序 变量 数据模型操作 系列索引 本文版权归mephisto和博客园共有,欢迎转载,但须保留此段声明,并给出原文链接,谢谢合作. 文章是哥(mephisto)写的,SourceLink 序 ...

随机推荐

  1. 《UNIX编程环境》的源代码的第二个版本Ubuntu下编

    1.在http://www.apuebook.com下载源代码 2. 视图READ root@ubuntu:/home/wl/mywork/apue.2e# cat -n README 1 Read ...

  2. Nagios+pnp4nagios+rrdtool 安装配置nagios(一)

    基于的软件版本 Apache-2.0.63  php-5.3.2 nagios-3.2.3  nagios-plugins-1.4.15  rrdtool-1.4.5 nrpe-2.12 pnp4na ...

  3. mmc生产任务分配问题

    mmc生产任务分配问题,本题目简单.

  4. Qt之QComboBox(基本应用、代理设置)

    QComboBox下来列表比较常用,用户可以通过选择不同的选项来实现不同的操作,如何实现自己的下拉列表呢? 很多人在问QComboBox如何设置选项的高度.代理等一些问题!今天就在此分享一下自己的一些 ...

  5. hdu - 4975 - A simple Gaussian elimination problem.(最大流量)

    意甲冠军:要在N好M行和列以及列的数字矩阵和,每个元件的尺寸不超过9,询问是否有这样的矩阵,是独一无二的N(1 ≤ N ≤ 500) , M(1 ≤ M ≤ 500). 主题链接:http://acm ...

  6. J2EE请求和响应—Servlet

    一.什么是Servlet? Servlet是执行Webserver上的一个特殊Java类.其特殊用途是响应client请求并做出处理.使得client与server端进行交互. 二.生命周期  Ser ...

  7. 【Linux驱动】TQ2440 LED驱动程序

    ★整体介绍 LED驱动程序主要实现了TQ2440开发板上的4个LED灯的硬件驱动,实现了对引脚GPIOB5.GPIOB6.GPIOB7.GPIOB8的高低电平设置(common-smdk.c中已经实现 ...

  8. VirtualBox安装ubuntu14.04和文件共享

    因为机器的VMware使用很卡,占用更多的内存,所以我想,以取代VirtualBox.已安装ubuntu14.04使用与VMware在相同的. VirtualBox下载链接:https://www.v ...

  9. C语言中main函数的參数具体解释

    main函数的定义形式         main函数能够不带參数,也能够带參数,这个參数能够觉得是 main函数的形式參数.C语言规定main函数的參数仅仅能有两个,习惯上这两个參数写为argc和ar ...

  10. 利用ffmpeg将H264解码为RGB

    因为公司买到了一个不提供解码器的设备,我不得已还要做解码的工作.在网上找了一圈,H264解码比較方便的也就是ffmpeg一系列的函数库了,原本设备中也是用这套函数库解码,但厂家不给提供,没办法,仅仅得 ...