executeBatch()相关操作汇总

 

环境: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_idcreate  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

时间: 2024-09-29 15:52:23

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

iOS 文件及字符串相关操作汇总 - 持续更新中......

iOS 文件及字符串相关操作汇总 - 持续更新中...... 太阳火神的美丽人生 (http://blog.csdn.net/opengl_es) 本文遵循"署名-非商业用途-保持一致"创作公用协议 转载请保留此句:太阳火神的美丽人生 -  本博客专注于 敏捷开发及移动和物联设备研究:iOS.Android.Html5.Arduino.pcDuino,否则,出自本博客的文章拒绝转载或再转载,谢谢合作. 1.获取应用包中文件的绝对路径: NSString *absoluteFileNam

aliyun TableStore相关操作汇总

  总结:这个东西本身可能技术还不成熟,使用的人少,有问题很验证解决 遇到的问题:(1)没有一个GUI工具,使用门槛高(2)查询的GetRange不方便,把查询出来的数据使用System.out.println打印出来的是乱码(3)batch insert时报错及解析: 表格存储Table Store限制项:https://help.aliyun.com/knowledge_detail/38573.html BatchGetRow 一次操作请求读取的行数 不超过 100 N/ABatchWri

asp.net DataTable相关操作集锦(筛选,取前N条数据,去重复行,获取指定列数据等)_实用技巧

本文实例总结了asp.net DataTable相关操作.分享给大家供大家参考,具体如下: #region DataTable筛选,排序返回符合条件行组成的新DataTable或直接用DefaultView按条件返回 /// <summary> /// DataTable筛选,排序返回符合条件行组成的新DataTable或直接用DefaultView按条件返回 /// eg:SortExprDataTable(dt,"Sex='男'","Time Desc&quo

Yii2——使用数据库操作汇总(增删查改、事务)_php技巧

本文介绍了 Yii2--使用数据库操作汇总(增删查改.事务),具体如下: 对象操作 查询 //1.简单查询 $admin=Admin::model()->findAll($condition,$params); $admin=Admin::model()->findAll("username=:name",array(":name"=>$username)); $infoArr= NewsList::model()->findAll(&quo

js获取当前日期时间及其它日期操作汇总_javascript技巧

本文实例为大家分享了javascript时间操作的使用常见场景,供大家参考,具体内容如下 var myDate = new Date(); myDate.getYear(); //获取当前年份(2位) myDate.getFullYear(); //获取完整的年份(4位,1970-????) myDate.getMonth(); //获取当前月份(0-11,0代表1月) myDate.getDate(); //获取当前日(1-31) myDate.getDay(); //获取当前星期X(0-6,

CI框架中redis缓存相关操作文件示例代码_php实例

本文实例讲述了CI框架中redis缓存相关操作文件.分享给大家供大家参考,具体如下: redis缓存类文件位置: 'ci\system\libraries\Cache\drivers\Cache_redis.php' <?php /** * CodeIgniter * * An open source application development framework for PHP 5.2.4 or newer * * NOTICE OF LICENSE * * Licensed under

js获取当前日期时间及其它操作汇总_javascript技巧

js获取当前日期时间及其它操作汇总 var myDate = new Date(); myDate.getYear(); //获取当前年份(2位) myDate.getFullYear(); //获取完整的年份(4位,1970-????) myDate.getMonth(); //获取当前月份(0-11,0代表1月) myDate.getDate(); //获取当前日(1-31) myDate.getDay(); //获取当前星期X(0-6,0代表星期天) myDate.getTime(); /

路径,文件,目录,I/O常见操作汇总(三)

主要内容: 一.路径的相关操作,如判断路径是否合法,路径类型,路径的特定部分,合并路径,系统文件夹路径等内容: 二.相关通用文件对话框,这些对话框可以帮助我们操作文件系统中的文件和目录: 三.文件和目录操作,如复制.移动.删除.重命名,文件的版本信息,文件判等.搜索,读写文件等: 四.读写文件,对文件系统的监视: 五.其它,如临时文件,随机文件名等: 第一篇-路径的相关操作和通用文件对话框的使用 第二篇-文件和目录的相关操作 这一篇将介绍第四.五部分. 文件读写相关类介绍: 文件读写操作涉及的类

路径,文件,目录,I/O常见操作汇总(二)

摘要: 文件操作是程序中非常基础和重要的内容,而路径.文件.目录以及I/O都是在进行文件操作时的常见主题,这里想把这些常见的问题作个总结,对于每个问题,尽量提供一些解决方案,即使没有你想要的答案,也希望能提供给你一点有益的思路,如果你有好的建议,恳请能够留言,使这些内容更加完善. 主要内容: 一.路径的相关操作, 如判断路径是否合法,路径类型,路径的特定部分,合并路径,系统文件夹路径等内容: 二.相关通用文件对话框,这些对话框可以帮助我们操作文件系统中的文件和目录: 三.文件.目录.驱动器的操作