Example usage for java.sql Statement executeBatch

List of usage examples for java.sql Statement executeBatch

Introduction

In this page you can find the example usage for java.sql Statement executeBatch.

Prototype

int[] executeBatch() throws SQLException;

Source Link

Document

Submits a batch of commands to the database for execution and if all commands execute successfully, returns an array of update counts.

Usage

From source file:com.hangum.tadpole.importexport.core.dialogs.SQLToDBImportDialog.java

/**
 * select? execute  ./*from  w  w  w  . j  a  va2s  . co  m*/
 * 
 * @param listQuery
 * @throws Exception
 */
private int runSQLExecuteBatch(List<String> listQuery) throws Exception {
    java.sql.Connection conn = null;
    Statement statement = null;
    int result = 0;

    try {
        SqlMapClient client = TadpoleSQLManager.getInstance(userDB);
        conn = client.getDataSource().getConnection();
        conn.setAutoCommit(false);
        statement = conn.createStatement();
        int count = 0;

        for (String strQuery : listQuery) {
            if ("".equals(StringUtils.trimToEmpty(strQuery))) //$NON-NLS-1$
                continue;

            statement.addBatch(strQuery);
            if (++count % batchSize == 0) {
                try {
                    statement.executeBatch();
                } catch (SQLException e) {
                    logger.error("Execute Batch error", e); //$NON-NLS-1$
                    bufferBatchResult.append(e.getMessage() + "\n"); //$NON-NLS-1$

                    SQLException ne = e.getNextException();
                    while (ne != null) {
                        logger.error("NEXT SQLException is ", ne);//$NON-NLS-1$
                        bufferBatchResult.append(ne.getMessage() + "\n"); //$NON-NLS-1$
                        ne = ne.getNextException();
                    }

                    if (btnIgnore.getSelection()) {
                        conn.commit();
                        continue;
                    } else {
                        conn.rollback();
                        result = -1;
                        break;
                    }
                }
            }
        }

        statement.executeBatch();
        conn.commit();
        conn.setAutoCommit(true);

        if (result < 0 && !"".equals(bufferBatchResult.toString())) { //$NON-NLS-1$
            MessageDialog.openWarning(null, Messages.get().Warning, bufferBatchResult.toString());
        }
    } catch (SQLException e) {
        logger.error("Execute Batch error", e); //$NON-NLS-1$
        bufferBatchResult.append(e.getMessage() + "\n"); //$NON-NLS-1$
        if (btnIgnore.getSelection()) {
            conn.commit();
        } else {
            conn.rollback();
        }

        SQLException ne = e.getNextException();
        while (ne != null) {
            logger.error("Execute Batch error", e); //$NON-NLS-1$
            bufferBatchResult.append(e.getMessage() + "\n"); //$NON-NLS-1$
            ne = ne.getNextException();
        }
    } catch (Exception e) {
        result = -1;
        logger.error("Execute Batch error", e); //$NON-NLS-1$
        bufferBatchResult.append(e.getMessage() + "\n"); //$NON-NLS-1$
        conn.rollback();
        throw e;
    } finally {
        try {
            if (statement != null)
                statement.close();
        } catch (Exception e) {
        }
        try {
            if (conn != null)
                conn.close();
        } catch (Exception e) {
        }
    }
    return result;
}

From source file:it.cnr.icar.eric.server.persistence.rdb.AbstractDAO.java

/**
 * @see it.cnr.icar.eric.server.persistence.rdb.OMARDAO#update(org.oasis.ebxml.registry.bindings.rim.UserType, java.sql.Connection, java.util.List, java.util.HashMap)
 *///from w w w.j  av  a 2s .  com
public void update(@SuppressWarnings("rawtypes") List objects) throws RegistryException {

    //Return immediatley if no objects to insert
    if (objects.size() == 0) {
        return;
    }

    log.trace(ServerResourceBundle.getInstance().getString("message.UpdatingRowsInTable",
            new Object[] { new Integer(objects.size()), getTableName() }));
    action = DAO_ACTION_UPDATE;

    Statement stmt = null;

    try {
        stmt = context.getConnection().createStatement();
        Iterator<?> iter = objects.iterator();
        while (iter.hasNext()) {
            Object obj = iter.next();

            prepareToUpdate(obj);

            String str = getSQLStatementFragment(obj);
            log.trace("stmt = " + str);
            stmt.addBatch(str);
        }

        @SuppressWarnings("unused")
        int[] updateCounts = stmt.executeBatch();

        iter = objects.iterator();
        while (iter.hasNext()) {
            Object obj = iter.next();

            onUpdate(obj);
        }

    } catch (SQLException e) {
        log.error(ServerResourceBundle.getInstance().getString("message.CaughtException1"), e);
        throw new RegistryException(e);
    } finally {
        closeStatement(stmt);
    }
}

From source file:com.google.enterprise.connector.salesforce.storetype.DBStore.java

public DBStore(BaseConnector connector) {
    Connection connection = null;

    logger = Logger.getLogger(this.getClass().getPackage().getName());
    logger.log(Level.INFO, "Initialize DBStore  ");
    this.connector = connector;
    //each connector instance has its own table in the same database
    this.instance_table = "i_" + connector.getInstanceName();

    Statement Stmt = null;//from  www. j  a v  a2 s.  c  om
    ResultSet RS = null;
    DatabaseMetaData dbm = null;

    boolean table_exists = false;

    try {
        //check if the datasource/database exists
        Context initCtx = new InitialContext();
        Context envCtx = (Context) initCtx.lookup("java:comp/env");
        ds = (DataSource) envCtx.lookup(BaseConstants.CONNECTOR_DATASOURCE);
        connection = ds.getConnection();
        connection.setAutoCommit(true);
        dbm = connection.getMetaData();
        logger.log(Level.INFO, "Connected to databaseType " + dbm.getDatabaseProductName());
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Exception initializing Store Datasource " + ex);
        connection = null;
        return;
    }

    try {
        if (dbm.getDatabaseProductName().equals("MySQL")) {

            //check if the per-connector table exists
            logger.log(Level.FINE, "Checking to see if  connector DB exists...");
            Stmt = connection.createStatement();
            RS = Stmt.executeQuery("desc " + instance_table);
            ResultSetMetaData rsMetaData = RS.getMetaData();
            if (rsMetaData.getColumnCount() > 0)
                table_exists = true;

            RS.close();
            Stmt.close();
        } else {
            logger.log(Level.SEVERE, "Unsupported DATABASE TYPE..." + dbm.getDatabaseProductName());
        }

    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Exception initializing Store " + ex);
    }

    try {
        //if the per-instance table doesn't exist, create it
        if (!table_exists) {
            logger.log(Level.INFO, "Creating Instance Table " + instance_table);

            if (dbm.getDatabaseProductName().equals("MySQL")) {
                Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                        ResultSet.CONCUR_READ_ONLY);
                String create_stmt = "";

                create_stmt = "CREATE TABLE  `" + this.instance_table + "` ("
                        + "`crawl_set` decimal(19,5) NOT NULL,"
                        + "`insert_timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,"
                        + "`crawl_data` MEDIUMTEXT default NULL," + "PRIMARY KEY  (`crawl_set`),"
                        + "KEY `set_index` (`crawl_set`)" + ") ENGINE=MyISAM;";
                statement.addBatch(create_stmt);
                statement.executeBatch();
                statement.close();
            } else {
                logger.log(Level.INFO, "Instance Table " + instance_table + " already exists");
                //connection.close();
                //TODO: somehow figure out if we should delete this table here
            }
        }

        boolean qrtz_table_exists = false;
        if (dbm.getDatabaseProductName().equals("MySQL")) {

            //check if the per-connector table exists
            logger.log(Level.FINE, "Checking to see if  quartz tables exists...");
            Stmt = connection.createStatement();
            try {
                RS = Stmt.executeQuery("desc QRTZ_JOB_DETAILS");
                ResultSetMetaData rsMetaData = RS.getMetaData();
                if (rsMetaData.getColumnCount() > 0)
                    qrtz_table_exists = true;
            } catch (Exception ex) {
                logger.log(Level.INFO, "Could not find Quartz Tables...creating now..");
            }
            RS.close();
            Stmt.close();
        } else {
            logger.log(Level.SEVERE, "Unsupported DATABASE TYPE..." + dbm.getDatabaseProductName());
        }

        if (!qrtz_table_exists) {
            logger.log(Level.INFO, "Creating Global Quartz Table ");
            //the quartz db setup scripts are at
            //quartz-1.8.0/docs/dbTables/tables_mysql.sql
            //one set of Quartz tables can handle any number of triggers/crons
            Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);

            String create_stmt = "CREATE TABLE QRTZ_JOB_DETAILS (JOB_NAME  VARCHAR(200) NOT NULL,JOB_GROUP VARCHAR(200) NOT NULL,DESCRIPTION VARCHAR(250) NULL,JOB_CLASS_NAME   VARCHAR(250) NOT NULL,IS_DURABLE VARCHAR(1) NOT NULL,IS_VOLATILE VARCHAR(1) NOT NULL,IS_STATEFUL VARCHAR(1) NOT NULL,REQUESTS_RECOVERY VARCHAR(1) NOT NULL,JOB_DATA BLOB NULL,PRIMARY KEY (JOB_NAME,JOB_GROUP));";
            statement.addBatch(create_stmt);
            create_stmt = "CREATE TABLE QRTZ_JOB_LISTENERS  (    JOB_NAME  VARCHAR(200) NOT NULL,    JOB_GROUP VARCHAR(200) NOT NULL,    JOB_LISTENER VARCHAR(200) NOT NULL,    PRIMARY KEY (JOB_NAME,JOB_GROUP,JOB_LISTENER),    FOREIGN KEY (JOB_NAME,JOB_GROUP)    REFERENCES QRTZ_JOB_DETAILS(JOB_NAME,JOB_GROUP));";
            statement.addBatch(create_stmt);
            create_stmt = "CREATE TABLE QRTZ_FIRED_TRIGGERS  (    ENTRY_ID VARCHAR(95) NOT NULL,    TRIGGER_NAME VARCHAR(200) NOT NULL,    TRIGGER_GROUP VARCHAR(200) NOT NULL,    IS_VOLATILE VARCHAR(1) NOT NULL,    INSTANCE_NAME VARCHAR(200) NOT NULL,    FIRED_TIME BIGINT(13) NOT NULL,    PRIORITY INTEGER NOT NULL,    STATE VARCHAR(16) NOT NULL,    JOB_NAME VARCHAR(200) NULL,    JOB_GROUP VARCHAR(200) NULL,    IS_STATEFUL VARCHAR(1) NULL,    REQUESTS_RECOVERY VARCHAR(1) NULL,    PRIMARY KEY (ENTRY_ID));";
            statement.addBatch(create_stmt);
            create_stmt = "CREATE TABLE QRTZ_TRIGGERS  (    TRIGGER_NAME VARCHAR(200) NOT NULL,    TRIGGER_GROUP VARCHAR(200) NOT NULL,    JOB_NAME  VARCHAR(200) NOT NULL,    JOB_GROUP VARCHAR(200) NOT NULL,    IS_VOLATILE VARCHAR(1) NOT NULL,    DESCRIPTION VARCHAR(250) NULL,    NEXT_FIRE_TIME BIGINT(13) NULL,    PREV_FIRE_TIME BIGINT(13) NULL,    PRIORITY INTEGER NULL,    TRIGGER_STATE VARCHAR(16) NOT NULL,    TRIGGER_TYPE VARCHAR(8) NOT NULL,    START_TIME BIGINT(13) NOT NULL,    END_TIME BIGINT(13) NULL,    CALENDAR_NAME VARCHAR(200) NULL,    MISFIRE_INSTR SMALLINT(2) NULL,    JOB_DATA BLOB NULL,    PRIMARY KEY (TRIGGER_NAME,TRIGGER_GROUP),    FOREIGN KEY (JOB_NAME,JOB_GROUP)        REFERENCES QRTZ_JOB_DETAILS(JOB_NAME,JOB_GROUP));";
            statement.addBatch(create_stmt);
            create_stmt = "CREATE TABLE QRTZ_SIMPLE_TRIGGERS  (    TRIGGER_NAME VARCHAR(200) NOT NULL,    TRIGGER_GROUP VARCHAR(200) NOT NULL,    REPEAT_COUNT BIGINT(7) NOT NULL,    REPEAT_INTERVAL BIGINT(12) NOT NULL,    TIMES_TRIGGERED BIGINT(10) NOT NULL,    PRIMARY KEY (TRIGGER_NAME,TRIGGER_GROUP),    FOREIGN KEY (TRIGGER_NAME,TRIGGER_GROUP)        REFERENCES QRTZ_TRIGGERS(TRIGGER_NAME,TRIGGER_GROUP));";
            statement.addBatch(create_stmt);
            create_stmt = "CREATE TABLE QRTZ_CRON_TRIGGERS  (    TRIGGER_NAME VARCHAR(200) NOT NULL,    TRIGGER_GROUP VARCHAR(200) NOT NULL,    CRON_EXPRESSION VARCHAR(200) NOT NULL,    TIME_ZONE_ID VARCHAR(80),    PRIMARY KEY (TRIGGER_NAME,TRIGGER_GROUP),    FOREIGN KEY (TRIGGER_NAME,TRIGGER_GROUP)        REFERENCES QRTZ_TRIGGERS(TRIGGER_NAME,TRIGGER_GROUP));";
            statement.addBatch(create_stmt);
            create_stmt = "CREATE TABLE QRTZ_BLOB_TRIGGERS  (    TRIGGER_NAME VARCHAR(200) NOT NULL,    TRIGGER_GROUP VARCHAR(200) NOT NULL,    BLOB_DATA BLOB NULL,    PRIMARY KEY (TRIGGER_NAME,TRIGGER_GROUP),    FOREIGN KEY (TRIGGER_NAME,TRIGGER_GROUP)        REFERENCES QRTZ_TRIGGERS(TRIGGER_NAME,TRIGGER_GROUP));";
            statement.addBatch(create_stmt);
            create_stmt = "CREATE TABLE QRTZ_TRIGGER_LISTENERS  (    TRIGGER_NAME  VARCHAR(200) NOT NULL,    TRIGGER_GROUP VARCHAR(200) NOT NULL,    TRIGGER_LISTENER VARCHAR(200) NOT NULL,    PRIMARY KEY (TRIGGER_NAME,TRIGGER_GROUP,TRIGGER_LISTENER),    FOREIGN KEY (TRIGGER_NAME,TRIGGER_GROUP)        REFERENCES QRTZ_TRIGGERS(TRIGGER_NAME,TRIGGER_GROUP));";
            statement.addBatch(create_stmt);
            create_stmt = "CREATE TABLE QRTZ_CALENDARS  (    CALENDAR_NAME  VARCHAR(200) NOT NULL,    CALENDAR BLOB NOT NULL,    PRIMARY KEY (CALENDAR_NAME));";
            statement.addBatch(create_stmt);
            create_stmt = "CREATE TABLE QRTZ_PAUSED_TRIGGER_GRPS  (    TRIGGER_GROUP  VARCHAR(200) NOT NULL,     PRIMARY KEY (TRIGGER_GROUP));";
            statement.addBatch(create_stmt);
            create_stmt = "CREATE TABLE QRTZ_SCHEDULER_STATE  (    INSTANCE_NAME VARCHAR(200) NOT NULL,    LAST_CHECKIN_TIME BIGINT(13) NOT NULL,    CHECKIN_INTERVAL BIGINT(13) NOT NULL,    PRIMARY KEY (INSTANCE_NAME));";
            statement.addBatch(create_stmt);
            create_stmt = "CREATE TABLE QRTZ_LOCKS  (    LOCK_NAME  VARCHAR(40) NOT NULL,     PRIMARY KEY (LOCK_NAME));";
            statement.addBatch(create_stmt);
            create_stmt = "INSERT INTO QRTZ_LOCKS values('TRIGGER_ACCESS');";
            statement.addBatch(create_stmt);
            create_stmt = "INSERT INTO QRTZ_LOCKS values('JOB_ACCESS');";
            statement.addBatch(create_stmt);
            create_stmt = "INSERT INTO QRTZ_LOCKS values('CALENDAR_ACCESS');";
            statement.addBatch(create_stmt);
            create_stmt = "INSERT INTO QRTZ_LOCKS values('STATE_ACCESS');";
            statement.addBatch(create_stmt);
            create_stmt = "INSERT INTO QRTZ_LOCKS values('MISFIRE_ACCESS');";
            statement.addBatch(create_stmt);
            statement.executeBatch();
            statement.close();
        } else {
            logger.log(Level.INFO, "Global Quartz Table already exists ");
        }
        connection.close();

    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Exception Creating StoreTable " + ex);
    }
}

From source file:it.cnr.icar.eric.server.persistence.rdb.AbstractDAO.java

/**
 * Does a bulk delete of a Collection of objects that match the type for this persister.
 *
 *///from  ww  w. j av a2  s . c  om
public void delete(@SuppressWarnings("rawtypes") List objects) throws RegistryException {
    //Return immediatley if no objects to insert
    if (objects.size() == 0) {
        return;
    }

    log.trace(ServerResourceBundle.getInstance().getString("message.DeletingRowsInTable",
            new Object[] { new Integer(objects.size()), getTableName() }));
    action = DAO_ACTION_DELETE;

    Statement stmt = null;

    try {
        stmt = context.getConnection().createStatement();
        @SuppressWarnings("rawtypes")
        Iterator iter = objects.iterator();
        while (iter.hasNext()) {
            Object obj = iter.next();

            prepareToDelete(obj);

            String str = getSQLStatementFragment(obj);
            log.trace("stmt = " + str);
            stmt.addBatch(str);
        }

        @SuppressWarnings("unused")
        int[] updateCounts = stmt.executeBatch();

        iter = objects.iterator();
        while (iter.hasNext()) {
            Object obj = iter.next();

            onDelete(obj);
        }

    } catch (SQLException e) {
        log.error(ServerResourceBundle.getInstance().getString("message.CaughtException1"), e);
        throw new RegistryException(e);
    } finally {
        closeStatement(stmt);
    }
}

From source file:com.edgenius.wiki.installation.DBLoader.java

public void resetDB(String type, ConnectionProxy con, String dbname, String username, String password)
        throws SQLException, IOException {
    Statement stat = null;
    try {/*from   ww  w  .j  av  a2 s  .  co m*/
        log.info("Reset database " + dbname + " starting...");
        dbname = StringUtils.trimToEmpty(dbname);
        username = StringUtils.trimToEmpty(username);
        password = StringUtils.trimToEmpty(password);
        stat = con.createStatement();

        List<String> lines = loadSQLFile(type, type + "-create-db.sql");
        for (String sql : lines) {
            sql = sql.replaceAll("@TOKEN.DATABASE.NAME@", dbname);
            sql = sql.replaceAll("@TOKEN.DATABASE.USERNAME@", username);
            sql = sql.replaceAll("@TOKEN.DATABASE.PASSWORD@", password);
            stat.addBatch(sql);
        }
        stat.executeBatch();

        log.info("Database " + dbname + " reset success");
    } finally {
        if (stat != null)
            stat.close();
    }

}

From source file:org.kuali.kra.infrastructure.TestUtilities.java

License:asdf

public static void clearTables(final PlatformTransactionManager transactionManager, final DataSource dataSource,
        final String edenSchemaName, final List<String> dontClear) {
    LOG.info("Clearing tables for schema " + edenSchemaName);
    if (dataSource == null) {
        Assert.fail("Null data source given");
    }/* w  ww .ja v a  2s .com*/
    if (edenSchemaName == null || edenSchemaName.equals("")) {
        Assert.fail("Empty eden schema name given");
    }
    new TransactionTemplate(transactionManager).execute(new TransactionCallback() {
        public Object doInTransaction(TransactionStatus status) {
            verifyTestEnvironment(dataSource);
            JdbcTemplate template = new JdbcTemplate(dataSource);
            return template.execute(new StatementCallback() {
                public Object doInStatement(Statement statement) throws SQLException {
                    List<String> reEnableConstraints = new ArrayList<String>();
                    ResultSet resultSet = statement.getConnection().getMetaData().getTables(null,
                            edenSchemaName, null, new String[] { "TABLE" });
                    while (resultSet.next()) {
                        String tableName = resultSet.getString("TABLE_NAME");
                        if (tableName.startsWith("EN_") && !dontClear.contains(tableName)) {
                            ResultSet keyResultSet = statement.getConnection().getMetaData()
                                    .getExportedKeys(null, edenSchemaName, tableName);
                            while (keyResultSet.next()) {
                                String fkName = keyResultSet.getString("FK_NAME");
                                String fkTableName = keyResultSet.getString("FKTABLE_NAME");
                                statement.addBatch(
                                        "ALTER TABLE " + fkTableName + " DISABLE CONSTRAINT " + fkName);
                                reEnableConstraints
                                        .add("ALTER TABLE " + fkTableName + " ENABLE CONSTRAINT " + fkName);
                            }
                            keyResultSet.close();
                            statement.addBatch("DELETE FROM " + tableName.toUpperCase());
                        }
                    }
                    for (String constraint : reEnableConstraints) {
                        statement.addBatch(constraint);
                    }
                    statement.executeBatch();
                    resultSet.close();
                    return null;
                }
            });
        }
    });
    LOG.info("Tables successfully cleared for schema " + edenSchemaName);
}

From source file:com.wso2telco.workflow.dao.WorkflowDbService.java

/**
 * Application entry./*from  w  ww .j  a  va2s. c  om*/
 *
 * @param applicationid the applicationid
 * @param operators     the operators
 * @return the integer
 * @throws Exception the exception
 */

public void applicationEntry(int applicationid, Integer[] operators) throws SQLException, BusinessException {

    Connection con = null;
    Statement st = null;

    try {
        con = DbUtils.getDbConnection(DataSourceNames.WSO2TELCO_DEP_DB);

        if (con == null) {
            throw new Exception("Connection not found");
        }
        con.setAutoCommit(false);
        st = con.createStatement();
        for (Integer d : operators) {
            if (!operatorAppsIsExist(applicationid, d)) {
                StringBuilder query = new StringBuilder();
                query.append("INSERT INTO operatorapps (applicationid,operatorid) ");
                query.append("VALUES (" + applicationid + "," + d + ")");
                st.addBatch(query.toString());
            }
        }
        st.executeBatch();
        con.commit();

    } catch (SQLException e) {
        throw new SQLException();
    } catch (Exception e) {
        throw new BusinessException(GenaralError.UNDEFINED);
    } finally {
        DbUtils.closeAllConnections(st, con, null);
    }

}

From source file:org.apache.tajo.catalog.store.DBStore.java

private void upgrade(int from, int to) throws SQLException {
    String sql;//from w w  w .j a  va  2 s .  c om
    Statement stmt;
    if (from == 0) {
        if (to == 1) {
            sql = "DROP INDEX idx_options_key";
            LOG.info(sql);

            stmt = conn.createStatement();
            stmt.addBatch(sql);

            sql = "CREATE INDEX idx_options_key on " + TB_OPTIONS + " (" + C_TABLE_ID + ")";
            stmt.addBatch(sql);
            LOG.info(sql);
            stmt.executeBatch();
            stmt.close();

            LOG.info("DB Upgraded from " + from + " to " + to);
        } else {
            LOG.info("DB Upgraded from " + from + " to " + to);
        }
    }
}

From source file:com.mysql.stresstool.RunnableQueryInsertPartRange.java

public int[] executeSQL(Statement stmt) throws Exception {
    int[] iLine = new int[0];
    try {//from www.  ja  v  a  2 s  .  c  o  m
        iLine = stmt.executeBatch();
        stmt.clearBatch();
    } catch (SQLException sqle) {
        if ((sqle.getErrorCode() == 1205) && lockRetry < 4) {
            lockRetry++;
            System.out.println("Lock Found for thread = " + Thread.currentThread().getId() + " repeat N: "
                    + lockRetry + " OF 3");
            iLine = executeSQL(stmt);
            try {
                iLine = executeSQL(stmt);
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                System.out.println("Error from JDBC for thread = " + Thread.currentThread().getId() + " | "
                        + sqle.getErrorCode() + " : " + sqle.getMessage()
                        + "\n Reducing the FLOW and try to recover transaction");
                Thread.sleep(2000);
                executeSQL(stmt);
                // TODO Auto-generated catch block
                System.out.println("========= Reporting stack trace for debug =========");
                e.printStackTrace();
            }
        } else if (sqle.getErrorCode() > 0 && sqle.getErrorCode() != 1205 && lockRetry < 4) {
            lockRetry++;
            System.out.println("ERROR Found for thread = " + Thread.currentThread().getId() + " repeat N: "
                    + lockRetry + " OF 3");

            try {
                iLine = executeSQL(stmt);
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                System.out.println("Error from JDBC for thread = " + Thread.currentThread().getId() + " | "
                        + sqle.getErrorCode() + " : " + sqle.getMessage()
                        + "\n Reducing the FLOW and try to recover transaction");
                Thread.sleep(2000);
                executeSQL(stmt);
                // TODO Auto-generated catch block
                System.out.println("========= Reporting stack trace for debug =========");
                e.printStackTrace();
            }

        } else if (lockRetry >= 4) {
            stmt.clearBatch();
            try {
                stmt.execute("ROLLBACK");
            } catch (Exception eex) {
            }
            lockRetry = 0;
            System.out.println("Error from JDBC  for thread = " + Thread.currentThread().getId() + " | "
                    + sqle.getErrorCode() + " : " + sqle.getMessage() + " Aborting");
            //throw new Exception(sqle);
            return iLine;
        }

    } catch (Exception ex) {
        throw new Exception(ex);

    }

    return iLine;
}

From source file:it.cnr.icar.eric.server.persistence.rdb.AbstractDAO.java

/**
 * @see it.cnr.icar.eric.server.persistence.rdb.OMARDAO#insert(org.oasis.ebxml.registry.bindings.rim.UserType, java.sql.Connection, java.util.List, java.util.HashMap)
 *///from w  ww .  jav  a  2  s. c  o m
@SuppressWarnings("unchecked")
public void insert(@SuppressWarnings("rawtypes") List objects) throws RegistryException {

    //Return immediatley if no objects to insert
    if (objects.size() == 0) {
        return;
    }

    //First process any objects that may already exists in persistence layer
    objects = processExistingObjects(objects);

    //Return immediately if no objects to insert
    if (objects.size() == 0) {
        return;
    }

    log.trace(ServerResourceBundle.getInstance().getString("message.InsertingRowsInTable",
            new Object[] { new Integer(objects.size()), getTableName() }));
    action = DAO_ACTION_INSERT;

    Statement stmt = null;

    try {
        stmt = context.getConnection().createStatement();
        Iterator<ExtrinsicObjectType> iter = objects.iterator();
        while (iter.hasNext()) {
            Object obj = iter.next();

            String str = getSQLStatementFragment(obj);
            log.trace("stmt = " + str);
            stmt.addBatch(str);

            prepareToInsert(obj);
        }

        long startTime = System.currentTimeMillis();
        log.trace("AbstractDAO.insert: doing executeBatch");
        @SuppressWarnings("unused")
        int[] updateCounts = stmt.executeBatch();
        long endTime = System.currentTimeMillis();
        log.trace("AbstractDAO.insert: done executeBatch elapedTimeMillis=" + (endTime - startTime));

        iter = objects.iterator();
        while (iter.hasNext()) {
            Object obj = iter.next();

            onInsert(obj);
        }

    } catch (SQLException e) {
        log.error(ServerResourceBundle.getInstance().getString("message.CaughtException1"), e);
        throw new RegistryException(e);
    } finally {
        closeStatement(stmt);
    }

}