Example usage for java.sql PreparedStatement executeBatch

List of usage examples for java.sql PreparedStatement executeBatch

Introduction

In this page you can find the example usage for java.sql PreparedStatement 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.nextep.designer.dbgm.services.impl.DataService.java

@Override
public void addDataline(IDataSet set, IDataLine... lines) {
    Connection localConn = null;/* ww w.  j  a  v  a 2 s .  c  o  m*/
    PreparedStatement stmt = null;
    IStorageHandle handle = set.getStorageHandle();
    if (handle == null) {
        storageService.createDataSetStorage(set);
        handle = set.getStorageHandle();
    }
    try {
        localConn = storageService.getLocalConnection();
        final String insertStmt = handle.getInsertStatement();
        stmt = localConn.prepareStatement(insertStmt);
        for (IDataLine line : lines) {
            int col = 1;
            // For repository handles, we specify the row id
            // if (handle.isRepositoryHandle()) {
            if (line.getRowId() == 0) {
                stmt.setNull(col++, Types.BIGINT);
            } else {
                stmt.setLong(col++, line.getRowId());
            }
            // }
            // Processing line data
            for (IReference r : set.getColumnsRef()) {
                final IColumnValue value = line.getColumnValue(r);
                Object valueObj = null;
                if (value != null) {
                    valueObj = value.getValue();
                    if (valueObj != null) {
                        stmt.setObject(col, valueObj);
                    } else {
                        IBasicColumn c = (IBasicColumn) VersionHelper.getReferencedItem(r);
                        int jdbcType = storageService.getColumnSqlType(set, c);
                        stmt.setNull(col, jdbcType);
                    }
                }
                // Incrementing column index
                col++;

            }
            stmt.addBatch();
        }
        stmt.executeBatch();
        localConn.commit();
    } catch (SQLException e) {
        LOGGER.error(DBGMMessages.getString("service.data.addDatalineFailed") + e.getMessage(), //$NON-NLS-1$
                e);
    } finally {
        safeClose(null, stmt, localConn, false);
    }

}

From source file:org.rhq.enterprise.server.measurement.CallTimeDataManagerBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void insertCallTimeDataValues(Set<CallTimeData> callTimeDataSet) {
    int[] results;
    String insertValueSql;/*from  w w  w. j a  va 2 s.c  o  m*/
    PreparedStatement ps = null;
    Connection conn = null;

    try {
        conn = rhqDs.getConnection();
        DatabaseType dbType = DatabaseTypeFactory.getDatabaseType(conn);

        if (dbType instanceof Postgresql83DatabaseType) {
            Statement st = null;
            try {
                // Take advantage of async commit here
                st = conn.createStatement();
                st.execute("SET synchronous_commit = off");
            } finally {
                JDBCUtil.safeClose(st);
            }
        }

        if (dbType instanceof PostgresqlDatabaseType || dbType instanceof OracleDatabaseType
                || dbType instanceof H2DatabaseType) {
            String valueNextvalSql = JDBCUtil.getNextValSql(conn, "RHQ_calltime_data_value");
            insertValueSql = String.format(CALLTIME_VALUE_INSERT_STATEMENT, valueNextvalSql);
        } else if (dbType instanceof SQLServerDatabaseType) {
            insertValueSql = CALLTIME_VALUE_INSERT_STATEMENT_AUTOINC;
        } else {
            throw new IllegalArgumentException("Unknown database type, can't continue: " + dbType);
        }

        ps = conn.prepareStatement(insertValueSql);
        for (CallTimeData callTimeData : callTimeDataSet) {
            ps.setInt(7, callTimeData.getScheduleId());
            Set<String> callDestinations = callTimeData.getValues().keySet();
            for (String callDestination : callDestinations) {
                CallTimeDataValue callTimeDataValue = callTimeData.getValues().get(callDestination);
                ps.setLong(1, callTimeDataValue.getBeginTime());
                ps.setLong(2, callTimeDataValue.getEndTime());
                ps.setDouble(3, callTimeDataValue.getMinimum());
                ps.setDouble(4, callTimeDataValue.getMaximum());
                ps.setDouble(5, callTimeDataValue.getTotal());
                ps.setLong(6, callTimeDataValue.getCount());
                ps.setString(8, callDestination);
                ps.addBatch();
            }
        }

        results = ps.executeBatch();

        int insertedRowCount = 0;
        for (int i = 0; i < results.length; i++) {
            if ((results[i] != 1) && (results[i] != -2)) // Oracle likes to return -2 becuase it doesn't track batch update counts
            {
                throw new MeasurementStorageException("Failed to insert call-time data value rows - result ["
                        + results[i] + "] for batch command [" + i + "] does not equal 1.");
            }

            insertedRowCount += results[i] == -2 ? 1 : results[i]; // If Oracle returns -2, just count 1 row;
        }

        notifyAlertConditionCacheManager("insertCallTimeDataValues",
                callTimeDataSet.toArray(new CallTimeData[callTimeDataSet.size()]));

        if (insertedRowCount > 0) {
            MeasurementMonitor.getMBean().incrementCalltimeValuesInserted(insertedRowCount);

            log.debug("Inserted " + insertedRowCount + " call-time data value rows.");
        }

    } catch (SQLException e) {
        logSQLException("Failed to persist call-time data values", e);
    } catch (Throwable t) {
        log.error("Failed to persist call-time data values", t);
    } finally {
        JDBCUtil.safeClose(conn, ps, null);
    }

}

From source file:org.springframework.jdbc.core.JdbcTemplateTests.java

public void testInterruptibleBatchUpdate() throws Exception {
    final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?";
    final int[] ids = new int[] { 100, 200 };
    final int[] rowsAffected = new int[] { 1, 2 };

    MockControl ctrlPreparedStatement = MockControl.createControl(PreparedStatement.class);
    PreparedStatement mockPreparedStatement = (PreparedStatement) ctrlPreparedStatement.getMock();
    mockPreparedStatement.getConnection();
    ctrlPreparedStatement.setReturnValue(mockConnection);
    mockPreparedStatement.setInt(1, ids[0]);
    ctrlPreparedStatement.setVoidCallable();
    mockPreparedStatement.addBatch();//  w  w  w  . j  ava2  s  . c  o m
    ctrlPreparedStatement.setVoidCallable();
    mockPreparedStatement.setInt(1, ids[1]);
    ctrlPreparedStatement.setVoidCallable();
    mockPreparedStatement.addBatch();
    ctrlPreparedStatement.setVoidCallable();
    mockPreparedStatement.executeBatch();
    ctrlPreparedStatement.setReturnValue(rowsAffected);
    if (debugEnabled) {
        mockPreparedStatement.getWarnings();
        ctrlPreparedStatement.setReturnValue(null);
    }
    mockPreparedStatement.close();
    ctrlPreparedStatement.setVoidCallable();

    MockControl ctrlDatabaseMetaData = MockControl.createControl(DatabaseMetaData.class);
    DatabaseMetaData mockDatabaseMetaData = (DatabaseMetaData) ctrlDatabaseMetaData.getMock();
    mockDatabaseMetaData.getDatabaseProductName();
    ctrlDatabaseMetaData.setReturnValue("MySQL");
    mockDatabaseMetaData.supportsBatchUpdates();
    ctrlDatabaseMetaData.setReturnValue(true);

    mockConnection.prepareStatement(sql);
    ctrlConnection.setReturnValue(mockPreparedStatement);
    mockConnection.getMetaData();
    ctrlConnection.setReturnValue(mockDatabaseMetaData, 2);

    ctrlPreparedStatement.replay();
    ctrlDatabaseMetaData.replay();
    replay();

    BatchPreparedStatementSetter setter = new InterruptibleBatchPreparedStatementSetter() {
        public void setValues(PreparedStatement ps, int i) throws SQLException {
            if (i < ids.length) {
                ps.setInt(1, ids[i]);
            }
        }

        public int getBatchSize() {
            return 1000;
        }

        public boolean isBatchExhausted(int i) {
            return (i >= ids.length);
        }
    };

    JdbcTemplate template = new JdbcTemplate(mockDataSource, false);

    int[] actualRowsAffected = template.batchUpdate(sql, setter);
    assertTrue("executed 2 updates", actualRowsAffected.length == 2);
    assertEquals(rowsAffected[0], actualRowsAffected[0]);
    assertEquals(rowsAffected[1], actualRowsAffected[1]);

    ctrlPreparedStatement.verify();
    ctrlDatabaseMetaData.verify();
}

From source file:at.rocworks.oa4j.logger.dbs.NoSQLJDBC.java

public int storeData(DataList list) {
    try {//w  w w.  j  a  v  a2  s. c  om
        Connection conn = dataSourceWrite.getConnection();
        if (conn != null) {
            int i;
            DataItem item;
            EventItem event;
            Object tag;

            conn.setAutoCommit(false);
            PreparedStatement stmt;

            Date t1 = new Date();

            stmt = conn.prepareStatement(sqlInsertStmt);
            for (i = 0; i <= list.getHighWaterMark() && (item = list.getItem(i)) != null; i++) {
                if (!(item instanceof EventItem))
                    continue;
                event = (EventItem) item;
                ValueItem val = event.getValue();

                tag = this.getTagOfDp(event.getDp());
                if (tag == null)
                    continue;

                if (tag instanceof Long)
                    stmt.setLong(1, (Long) tag);
                else if (tag instanceof String)
                    stmt.setString(1, (String) tag);

                java.sql.Timestamp ts = new java.sql.Timestamp(event.getTimeMS());
                ts.setNanos(event.getNanos());

                stmt.setTimestamp(2, ts, cal);

                Double dval = val.getDouble();
                if (dval != null) {
                    stmt.setDouble(3, dval);
                } else {
                    stmt.setNull(3, Types.DOUBLE);
                }

                // value_string                    
                stmt.setString(4, val.getString());

                // value_timestamp
                if (val.getTimeMS() != null)
                    stmt.setTimestamp(5, new java.sql.Timestamp(val.getTimeMS()), cal);
                else
                    stmt.setNull(5, Types.TIMESTAMP);

                // status, manager, user
                if (event.hasAttributes()) {
                    stmt.setLong(6, event.getStatus());
                    stmt.setInt(7, event.getManager());
                    stmt.setInt(8, event.getUser());
                } else {
                    stmt.setNull(6, Types.INTEGER);
                    stmt.setNull(7, Types.INTEGER);
                    stmt.setNull(8, Types.INTEGER);
                }

                //JDebug.out.log(Level.FINE, "{0}:{1}/{2} [{3}]", new Object[] {i, element_id.toString(), ts.toString(), item.toString()});

                stmt.addBatch();
            }
            try {
                stmt.executeBatch(); // TODO check result? int[] res =
            } catch (BatchUpdateException ex) {
                JDebug.out.log(Level.SEVERE, "Batch exception {0} update count {1}.",
                        new Object[] { ex.getErrorCode(), ex.getUpdateCounts().length });
                JDebug.StackTrace(Level.SEVERE, ex);
            } catch (SQLException ex) {
                SQLException current = ex;
                do {
                    JDebug.out.log(Level.SEVERE, "SQL exception {0}.", new Object[] { ex.getErrorCode() });
                    JDebug.StackTrace(Level.SEVERE, current);
                } while ((current = current.getNextException()) != null);
                //                    for (i = 0; i <= list.getHighWaterMark() && (item = list.getItem(i)) != null; i++) {
                //                        JDebug.out.log(Level.INFO, "{0}", item.toJSONObject());
                //                    }
            }
            Date t2 = new Date();
            stmt.close();

            afterInsert(conn);

            conn.commit();
            conn.close();
            addServerStats(list.getHighWaterMark(), t2.getTime() - t1.getTime());
            return INoSQLInterface.OK;
        } else {
            JDebug.StackTrace(Level.SEVERE, "no connection!");
            return INoSQLInterface.ERR_REPEATABLE;
        }
    } catch (Exception ex) {
        JDebug.StackTrace(Level.SEVERE, ex);
        return INoSQLInterface.ERR_REPEATABLE;
    }
}

From source file:org.wso2.carbon.policy.mgt.core.dao.impl.PolicyDAOImpl.java

@Override
public Policy addPolicyToRole(List<String> rolesToAdd, Policy policy) throws PolicyManagerDAOException {
    Connection conn;/*www. java  2 s .co m*/
    PreparedStatement insertStmt = null;
    //        PreparedStatement deleteStmt = null;
    //        final List<String> currentRoles = this.getPolicy(policy.getId()).getRoles();
    //
    //        SetReferenceTransformer<String> transformer = new SetReferenceTransformer<String>();
    //
    //        transformer.transform(currentRoles, rolesToAdd);
    //        rolesToAdd = transformer.getObjectsToAdd();
    //        List<String> rolesToDelete = transformer.getObjectsToRemove();
    try {
        conn = this.getConnection();
        if (rolesToAdd.size() > 0) {
            String query = "INSERT INTO DM_ROLE_POLICY (ROLE_NAME, POLICY_ID) VALUES (?, ?)";
            insertStmt = conn.prepareStatement(query);
            for (String role : rolesToAdd) {
                insertStmt.setString(1, role);
                insertStmt.setInt(2, policy.getId());
                insertStmt.addBatch();
            }
            insertStmt.executeBatch();
        }
        //            if (rolesToDelete.size() > 0){
        //                String deleteQuery = "DELETE FROM DM_ROLE_POLICY WHERE ROLE_NAME=? AND POLICY_ID=?";
        //                deleteStmt = conn.prepareStatement(deleteQuery);
        //                for (String role : rolesToDelete) {
        //                    deleteStmt.setString(1, role);
        //                    deleteStmt.setInt(2, policy.getId());
        //                    deleteStmt.addBatch();
        //                }
        //                deleteStmt.executeBatch();
        //            }
    } catch (SQLException e) {
        throw new PolicyManagerDAOException("Error occurred while adding the role name with policy to database",
                e);
    } finally {
        PolicyManagementDAOUtil.cleanupResources(insertStmt, null);
    }
    return policy;
}

From source file:org.wso2.carbon.policy.mgt.core.dao.impl.PolicyDAOImpl.java

@Override
public Policy addPolicyToUser(List<String> usersToAdd, Policy policy) throws PolicyManagerDAOException {
    Connection conn;//from ww  w  .j a  v  a  2  s.  com
    PreparedStatement insertStmt = null;
    //        PreparedStatement deleteStmt = null;
    //        final List<String> currentUsers = this.getPolicy(policy.getId()).getUsers();
    //
    //        SetReferenceTransformer<String> transformer = new SetReferenceTransformer<String>();
    //
    //        transformer.transform(currentUsers, usersToAdd);
    //        usersToAdd = transformer.getObjectsToAdd();
    //        List<String> usersToDelete = transformer.getObjectsToRemove();
    try {
        conn = this.getConnection();
        if (usersToAdd.size() > 0) {
            String query = "INSERT INTO DM_USER_POLICY (POLICY_ID, USERNAME) VALUES (?, ?)";
            insertStmt = conn.prepareStatement(query);
            for (String username : usersToAdd) {
                insertStmt.setInt(1, policy.getId());
                insertStmt.setString(2, username);
                insertStmt.addBatch();
            }
            insertStmt.executeBatch();
        }
        //            if (usersToDelete.size() > 0){
        //                String deleteQuery = "DELETE FROM DM_USER_POLICY WHERE USERNAME=? AND POLICY_ID=?";
        //                deleteStmt = conn.prepareStatement(deleteQuery);
        //                for (String username : usersToDelete) {
        //                    deleteStmt.setString(1, username);
        //                    deleteStmt.setInt(2, policy.getId());
        //                    deleteStmt.addBatch();
        //                }
        //                deleteStmt.executeBatch();
        //            }

    } catch (SQLException e) {
        throw new PolicyManagerDAOException("Error occurred while adding the user name with policy to database",
                e);
    } finally {
        PolicyManagementDAOUtil.cleanupResources(insertStmt, null);
        //            PolicyManagementDAOUtil.cleanupResources(deleteStmt, null);
    }
    return policy;
}

From source file:com.streamsets.pipeline.lib.jdbc.JdbcMultiRowRecordWriter.java

@SuppressWarnings("unchecked")
private void processPartition(Connection connection, Multimap<Long, Record> partitions, Long partitionKey,
        List<OnRecordErrorException> errorRecords) throws SQLException, OnRecordErrorException {
    Collection<Record> partition = partitions.get(partitionKey);
    // Fetch the base insert query for this partition.
    SortedMap<String, String> columnsToParameters = getFilteredColumnsToParameters(getColumnsToParameters(),
            partition.iterator().next());

    // put all the records in a queue for consumption
    LinkedList<Record> queue = new LinkedList<>(partition);

    // compute number of rows per batch
    if (columnsToParameters.isEmpty()) {
        throw new OnRecordErrorException(Errors.JDBCDEST_22);
    }//from  w w w  .  ja  va 2  s. c o m
    int maxRowsPerBatch = maxPrepStmtParameters / columnsToParameters.size();

    PreparedStatement statement = null;

    // parameters are indexed starting with 1
    int paramIdx = 1;
    int rowCount = 0;
    while (!queue.isEmpty()) {
        // we're at the start of a batch.
        if (statement == null) {
            // instantiate the new statement
            statement = generatePreparedStatement(columnsToParameters,
                    // the next batch will have either the max number of records, or however many are left.
                    Math.min(maxRowsPerBatch, queue.size()), getTableName(), connection);
        }

        // process the next record into the current statement
        Record record = queue.removeFirst();
        for (String column : columnsToParameters.keySet()) {
            Field field = record.get(getColumnsToFields().get(column));
            Field.Type fieldType = field.getType();
            Object value = field.getValue();

            try {
                switch (fieldType) {
                case LIST:
                    List<Object> unpackedList = unpackList((List<Field>) value);
                    Array array = connection.createArrayOf(getSQLTypeName(fieldType), unpackedList.toArray());
                    statement.setArray(paramIdx, array);
                    break;
                case DATE:
                case DATETIME:
                    // Java Date types are not accepted by JDBC drivers, so we need to convert to java.sql.Date
                    java.util.Date date = field.getValueAsDatetime();
                    statement.setObject(paramIdx, new java.sql.Date(date.getTime()));
                    break;
                default:
                    statement.setObject(paramIdx, value, getColumnType(column));
                    break;
                }
            } catch (SQLException e) {
                LOG.error(Errors.JDBCDEST_23.getMessage(), column, fieldType.toString(), e);
                throw new OnRecordErrorException(record, Errors.JDBCDEST_23, column, fieldType.toString());
            }
            ++paramIdx;
        }

        rowCount++;

        // check if we've filled up the current batch
        if (rowCount == maxRowsPerBatch) {
            // time to execute the current batch
            statement.addBatch();
            statement.executeBatch();
            statement.close();
            statement = null;

            // reset our counters
            rowCount = 0;
            paramIdx = 1;
        }
    }

    // check if there are any records left. this should occur whenever there isn't *exactly* maxRowsPerBatch records in
    // this partition.
    if (statement != null) {
        statement.addBatch();
        statement.executeBatch();
        statement.close();
    }
}

From source file:org.freebxml.omar.server.persistence.rdb.SlotDAO.java

/**
 * @param parentInsert It should be set to true if Slot insert is part of new
 * RegistryObject insert (i.e. in the case        of SubmitObjectsRequest). It should
 * be set to false in the case of AddSlotsRequest because the parent of the
 * slot is expected to be already submitted by previous SubmitObjectRequest.
 * In the latter case whether the parents of the slots exist will be checked.
 *//*from  www . j a  v  a2  s.  c  om*/
public void insert(List slots, boolean parentInsert) throws RegistryException {
    PreparedStatement pstmt = null;

    String parentId = (String) parent;

    if (slots.size() == 0) {
        return;
    }

    try {
        String sql = "INSERT INTO " + getTableName() + " (sequenceId, " + "name_, slotType, value, parent)"
                + " VALUES(?, ?, ?, ?, ?)";
        pstmt = context.getConnection().prepareStatement(sql);

        List duplicateSlotsNames = getDuplicateSlots(slots);

        if (duplicateSlotsNames.size() > 0) {
            // Some slots have duplicate name
            throw new DuplicateSlotsException(parentId, duplicateSlotsNames);
        }

        RegistryObjectDAO roDAO = new RegistryObjectDAO(context);

        // Check whether the parent exist in database, in case the parent
        // has been inserted by the previous SubmitObjectsRequest
        // (i.e. in the case of AddSlotsRequest)
        if (!parentInsert && !roDAO.registryObjectExist(parentId)) {
            // The parent does not exist
            throw new SlotsParentNotExistException(parentId);
        }
        /* HIEOS/BHT: Disabled for performance purposes.
        List slotsNamesAlreadyExist = slotsExist(parentId, slots);
                
        if (slotsNamesAlreadyExist.size() > 0) {
        // Some slots for this RegistryObject already exist
        throw new SlotsExistException(parentId, slotsNamesAlreadyExist);
        }*/

        Iterator iter = slots.iterator();
        Vector slotNames = new Vector();

        while (iter.hasNext()) {
            Slot slot = (Slot) iter.next();
            String slotName = slot.getName();
            String slotType = slot.getSlotType();
            List values = slot.getValueList().getValue();
            int size = values.size();

            for (int j = 0; j < size; j++) {
                String value = ((Value) values.get(j)).getValue();
                pstmt.setInt(1, j);
                pstmt.setString(2, slotName);
                pstmt.setString(3, slotType);
                pstmt.setString(4, value);
                pstmt.setString(5, parentId);
                log.trace("SQL = " + sql); // HIEOS/BHT: DEBUG (fix)
                pstmt.addBatch();
            }
        }

        if (slots.size() > 0) {
            int[] updateCounts = pstmt.executeBatch();
        }
    } catch (SQLException e) {
        log.error(ServerResourceBundle.getInstance().getString("message.CaughtException1"), e);
        throw new RegistryException(e);
    } finally {
        closeStatement(pstmt);
    }
}

From source file:com.viettel.logistic.wms.dao.SerialInventoryDAO.java

public ResultDTO insertListSerialInventoryBatch(List<SerialInventoryDTO> lstSerialInventoryDTO,
        Connection connection) {/* w w w.j ava  2s .c  o m*/
    ResultDTO resultDTO = new ResultDTO();
    //connection.
    //PREPARE STATEMENTS
    PreparedStatement prstmtInsertSerialInventory;
    //SQL
    StringBuilder sqlSerialInventory = new StringBuilder();

    int numberNeedToCommit = 0;
    int numberOfSuccess = 0;
    int numberOfFail = 0;
    //
    List paramsSerialInventory;
    //mac dinh la thanh cong
    resultDTO.setMessage(ParamUtils.SUCCESS);
    try {
        //1.KHOI TAO SESSION
        //2.1 TAO STATEMENTS SERIAL_INVENTORY
        sqlSerialInventory.append(" INSERT INTO serial_inventory(id, cust_id, cust_code, cust_name, stock_id,");
        sqlSerialInventory.append("       goods_id, goods_code, goods_name, goods_state,");
        sqlSerialInventory.append("       quantity, from_serial, to_serial, cell_code, barcode,");
        sqlSerialInventory.append(
                "       create_date, note, status, staff_id, staff_code,staff_name, inventory_code, goods_unit_type_name) ");
        sqlSerialInventory.append(
                " VALUES (SERIAL_INVENTORY_SEQ.nextval, TO_NUMBER(?), ?, ?, TO_NUMBER(?), TO_NUMBER(?), ");
        sqlSerialInventory.append(
                "  ?, ?, ?, TO_NUMBER(?), ?, ?, ?, ?, TO_DATE(?,'dd/MM/yyyy hh24:mi:ss'), ?, TO_NUMBER(?), ");
        sqlSerialInventory.append("  TO_NUMBER(?), ?, ?, ?, ? ) ");
        sqlSerialInventory.append(" LOG ERRORS REJECT LIMIT UNLIMITED ");
        //3. TAO PREPARE STATEMENT
        prstmtInsertSerialInventory = connection.prepareStatement(sqlSerialInventory.toString());
        //Chi tiet serial  
        for (SerialInventoryDTO serialInventoryDTO : lstSerialInventoryDTO) {
            numberNeedToCommit++;
            //SET PARAMS FOR SERIAL_INVENTORY
            paramsSerialInventory = setParamsSerialInventory(serialInventoryDTO);
            //SET PARAMS AND ADD TO BATCH
            for (int idx = 0; idx < paramsSerialInventory.size(); idx++) {
                prstmtInsertSerialInventory.setString(idx + 1,
                        DataUtil.nvl(paramsSerialInventory.get(idx), "").toString());
            }
            prstmtInsertSerialInventory.addBatch();

            if (numberNeedToCommit >= Constants.COMMIT_NUM) {
                try {
                    prstmtInsertSerialInventory.executeBatch();
                    numberOfSuccess = numberOfSuccess + numberNeedToCommit;
                } catch (Exception ex) {
                    numberOfFail = numberOfFail + numberNeedToCommit;
                }
                numberNeedToCommit = 0;
            }
        } //END FOR
        if (numberNeedToCommit > 0) {
            try {
                prstmtInsertSerialInventory.executeBatch();
                numberOfSuccess += numberNeedToCommit;
            } catch (Exception ex) {
                //connection.rollback();
                numberOfFail += numberNeedToCommit;
            }
        }
        prstmtInsertSerialInventory.close();
    } catch (SQLException | NumberFormatException e) {
        Logger.getLogger(StockGoodsSerialDAO.class.getName()).log(Level.SEVERE, null, e);
        resultDTO.setMessage(ParamUtils.FAIL);
    }

    //lay so luong hang hoa insert vao ban err$_
    List<StockGoodsSerialInforDTO> lstError = getListErrorSerialInventory(
            lstSerialInventoryDTO.get(0).getInventoryCode());
    int amountError = 0;
    if (lstError != null) {
        amountError = lstError.size();
    }
    int amountTotal = lstSerialInventoryDTO.size();
    numberOfSuccess = amountTotal - amountError;//So luong ban ghi insert thanh cong
    numberOfFail = amountError;//so luong hang loi da ton tai serial cua khach hang trong ban kiem ke
    //
    resultDTO.setQuantityFail(numberOfFail);
    resultDTO.setQuantitySucc(numberOfSuccess);
    resultDTO.setLstStockGoodsSerialInforDTO(lstError);
    // tra ve list serial loi
    return resultDTO;
}

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

/**
 * @param parentInsert It should be set to true if Slot insert is part of new
 * RegistryObject insert (i.e. in the case        of SubmitObjectsRequest). It should
 * be set to false in the case of AddSlotsRequest because the parent of the
 * slot is expected to be already submitted by previous SubmitObjectRequest.
 * In the latter case whether the parents of the slots exist will be checked.
 *//* w  ww  .j av  a 2  s.co  m*/
public void insert(List<?> slots, boolean parentInsert) throws RegistryException {
    PreparedStatement pstmt = null;

    String parentId = (String) parent;

    if (slots.size() == 0) {
        return;
    }

    try {
        String sql = "INSERT INTO " + getTableName() + " (sequenceId, " + "name_, slotType, value, parent)"
                + " VALUES(?, ?, ?, ?, ?)";
        pstmt = context.getConnection().prepareStatement(sql);

        List<String> duplicateSlotsNames = getDuplicateSlots(slots);

        if (duplicateSlotsNames.size() > 0) {
            // Some slots have duplicate name
            throw new DuplicateSlotsException(parentId, duplicateSlotsNames);
        }

        RegistryObjectDAO roDAO = new RegistryObjectDAO(context);

        // Check whether the parent exist in database, in case the parent
        // has been inserted by the previous SubmitObjectsRequest
        // (i.e. in the case of AddSlotsRequest)
        if (!parentInsert && !roDAO.registryObjectExist(parentId)) {
            // The parent does not exist
            throw new SlotsParentNotExistException(parentId);
        }

        List<String> slotsNamesAlreadyExist = slotsExist(parentId, slots);

        if (slotsNamesAlreadyExist.size() > 0) {
            // Some slots for this RegistryObject already exist
            throw new SlotsExistException(parentId, slotsNamesAlreadyExist);
        }

        Iterator<?> iter = slots.iterator();
        @SuppressWarnings("unused")
        Vector<Object> slotNames = new Vector<Object>();

        while (iter.hasNext()) {
            SlotType1 slot = (SlotType1) iter.next();
            String slotName = slot.getName();
            String slotType = slot.getSlotType();
            List<String> values = slot.getValueList().getValue();
            int size = values.size();

            for (int j = 0; j < size; j++) {
                String value = values.get(j);
                pstmt.setInt(1, j);
                pstmt.setString(2, slotName);
                pstmt.setString(3, slotType);
                pstmt.setString(4, value);
                pstmt.setString(5, parentId);

                log.trace("stmt = " + pstmt.toString());
                pstmt.addBatch();
            }
        }

        if (slots.size() > 0) {
            @SuppressWarnings("unused")
            int[] updateCounts = pstmt.executeBatch();
        }
    } catch (SQLException e) {
        log.error(ServerResourceBundle.getInstance().getString("message.CaughtException1"), e);
        throw new RegistryException(e);
    } finally {
        closeStatement(pstmt);
    }
}