Example usage for java.sql PreparedStatement addBatch

List of usage examples for java.sql PreparedStatement addBatch

Introduction

In this page you can find the example usage for java.sql PreparedStatement addBatch.

Prototype

void addBatch() throws SQLException;

Source Link

Document

Adds a set of parameters to this PreparedStatement object's batch of commands.

Usage

From source file:org.nuxeo.ecm.core.storage.sql.jdbc.JDBCRowMapper.java

/**
 * Updates multiple simple rows, all for the same table.
 *//*from  w  w  w . j  a  v  a2s  .c  o m*/
protected void updateSimpleRows(String tableName, List<RowUpdate> rows) throws StorageException {
    if (rows.isEmpty()) {
        return;
    }

    // reorganize by unique sets of keys + which ones are for delta updates
    Map<String, List<RowUpdate>> updatesByCanonKeys = new HashMap<>();
    Map<String, Collection<String>> keysByCanonKeys = new HashMap<>();
    Map<String, Set<String>> deltasByCanonKeys = new HashMap<>();
    for (RowUpdate rowu : rows) {
        List<String> keys = new ArrayList<String>(rowu.keys);
        if (keys.isEmpty()) {
            continue;
        }
        Set<String> deltas = new HashSet<>();
        for (ListIterator<String> it = keys.listIterator(); it.hasNext();) {
            String key = it.next();
            Serializable value = rowu.row.get(key);
            if (value instanceof Delta) {
                deltas.add(key);
                it.set(key + '+');
            }
        }
        Collections.sort(keys);
        String ck = StringUtils.join(keys, ','); // canonical keys
        List<RowUpdate> keysUpdates = updatesByCanonKeys.get(ck);
        if (keysUpdates == null) {
            updatesByCanonKeys.put(ck, keysUpdates = new LinkedList<RowUpdate>());
            keysByCanonKeys.put(ck, rowu.keys);
            deltasByCanonKeys.put(ck, deltas);
        }
        keysUpdates.add(rowu);
    }

    for (String ck : updatesByCanonKeys.keySet()) {
        List<RowUpdate> keysUpdates = updatesByCanonKeys.get(ck);
        Collection<String> keys = keysByCanonKeys.get(ck);
        Set<String> deltas = deltasByCanonKeys.get(ck);
        SQLInfoSelect update = sqlInfo.getUpdateById(tableName, keys, deltas);
        String loggedSql = supportsBatchUpdates && rows.size() > 1 ? update.sql + " -- BATCHED" : update.sql;
        try {
            PreparedStatement ps = connection.prepareStatement(update.sql);
            int batch = 0;
            try {
                for (RowUpdate rowu : keysUpdates) {
                    batch++;
                    if (logger.isLogEnabled()) {
                        logger.logSQL(loggedSql, update.whatColumns, rowu.row, deltas);
                    }
                    int i = 1;
                    for (Column column : update.whatColumns) {
                        Serializable value = rowu.row.get(column.getKey());
                        if (value instanceof Delta) {
                            value = ((Delta) value).getDeltaValue();
                        }
                        column.setToPreparedStatement(ps, i++, value);
                    }
                    if (supportsBatchUpdates) {
                        ps.addBatch();
                        if (batch % UPDATE_BATCH_SIZE == 0) {
                            int[] counts = ps.executeBatch();
                            countExecute();
                            logger.logCounts(counts);
                        }
                    } else {
                        int count = ps.executeUpdate();
                        countExecute();
                        logger.logCount(count);
                    }
                }
                if (supportsBatchUpdates) {
                    int[] counts = ps.executeBatch();
                    countExecute();
                    logger.logCounts(counts);
                }
            } finally {
                closeStatement(ps);
            }
        } catch (Exception e) {
            checkConnectionReset(e);
            throw new StorageException("Could not update: " + update.sql, e);
        }
    }
}

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

@Override
public void addDeviceGroupsToPolicy(Policy policy) throws PolicyManagerDAOException {

    Connection conn;//from   ww w  .j a v a 2 s  .co  m
    PreparedStatement stmt = null;
    List<DeviceGroupWrapper> deviceGroupWrappers = policy.getDeviceGroups();
    int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();

    try {
        conn = this.getConnection();
        String query = "INSERT INTO DM_DEVICE_GROUP_POLICY (DEVICE_GROUP_ID, POLICY_ID, TENANT_ID) VALUES (?, ?, ?)";
        stmt = conn.prepareStatement(query);
        for (DeviceGroupWrapper wrapper : deviceGroupWrappers) {
            stmt.setInt(1, wrapper.getId());
            stmt.setInt(2, policy.getId());
            stmt.setInt(3, tenantId);
            stmt.addBatch();
        }
        stmt.executeBatch();

    } catch (SQLException e) {
        throw new PolicyManagerDAOException(
                "Error occurred while adding the device group details to the policy.", e);
    } finally {
        PolicyManagementDAOUtil.cleanupResources(stmt, null);
    }
}

From source file:com.sec.ose.osi.sdk.protexsdk.discovery.DCCodeMatch.java

public boolean updateDB(String action, ArrayList<String> fileList,
        List<CodeMatchDiscovery> listCodeMatchDiscovery, String newComponentName,
        boolean isSelected_ThirdForthOption) {
    boolean remainPending = false;
    String componentID = "";
    String componentName = "";
    String versionID = "";
    String versionName = "";
    String filePath = "";
    String baseStatus = null;//from  www  .ja  va 2  s.  com

    log.debug(" # CodeMatchDiscovery update DB");

    if (action.equals("identify")) {
        baseStatus = DiscoveryAPIWrapper.STATE_PENDING;
    } else {
        baseStatus = DiscoveryAPIWrapper.STATE_REJECT;
    }
    log.debug("CodeMatchDiscovery update DB START : " + new java.util.Date());
    PreparedStatement prep = IdentificationDBManager.getCodeMatchUpdatePreparedStatement(projectName);
    PreparedStatement prep2 = IdentificationDBManager.updateIdentifiedTablePreparedStatement(projectName);
    int psCnt = 0;
    for (CodeMatchDiscovery cmd : listCodeMatchDiscovery) {
        String status = DiscoveryAPIWrapper.translateIdentficationStatus(cmd.getIdentificationStatus());
        // 1. code match table update
        if (baseStatus.equals(status)) {
            filePath = cmd.getFilePath().substring(1);
            if (fileList != null) {
                if (!fileList.contains(filePath))
                    continue;
            }
            componentID = cmd.getMatchingComponentId();
            versionID = cmd.getMatchingVersionId();
            if (versionID != null) {
                ComponentVersion cv = ComponentAPIWrapper.getComponentVersionById(componentID, versionID);
                if (cv != null) {
                    componentName = cv.getComponentName();
                    versionName = cv.getVersionName();
                }
            } else {
                componentName = ComponentAPIWrapper.getGlobalComponentName(componentID);
                versionName = "";
            }
            try {
                if (prep == null) {
                    continue;
                }
                prep.setString(1,
                        DiscoveryAPIWrapper.translateIdentficationStatus(cmd.getIdentificationStatus()));
                prep.setString(2, filePath);
                prep.setString(3, componentName);
                prep.setString(4, versionName);
                prep.addBatch();
                psCnt++;
                if (psCnt > 10000) {
                    IdentificationDBManager.executeUpdateStatement(prep);
                    psCnt = 0;
                }
            } catch (SQLException e) {
                log.warn(e);
            }
            remainPending = true;
        }

        // 2. identified table update
        if (isSelected_ThirdForthOption == true && action.equals("identify")
                && status.equals(DiscoveryAPIWrapper.STATE_IDENTIFIED)) {
            IdentificationDBManager.removeIdentifiedFile(projectName, cmd.getFilePath().substring(1),
                    TYPE_CODE_MATCH, cmd.getMatchingFileLocation().getFilePath());
            try {
                prep2.setString(1, cmd.getFilePath().substring(1)); // path
                prep2.setString(2, TYPE_CODE_MATCH); // match type
                prep2.setString(3, newComponentName); // component name
                prep2.setString(4, ""); // version name
                prep2.setString(5, ""); // license name
                prep2.setString(6, cmd.getMatchingFileLocation().getFilePath()); // matched_file
                prep2.addBatch();
            } catch (Exception e) {
                log.warn(e);
            }

        }
    }
    log.debug("Code Match Update START!! (It may delay...)");
    if (psCnt > 0) {
        IdentificationDBManager.executeUpdateStatement(prep);
    }
    log.debug("Code Match Update END..");
    IdentificationDBManager.executeUpdateStatement(prep2);

    if (prep != null) {
        try {
            prep.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    if (prep2 != null) {
        try {
            prep2.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    log.debug("CodeMatchDiscovery update DB END : " + new java.util.Date());
    return remainPending;
}

From source file:com.sec.ose.osi.sdk.protexsdk.discovery.report.ReportFactory.java

private static void insertCodematchTable(String projectName, ArrayList<CodeMatchesPrecision> list) {
    PreparedStatement prepCodematchTable = IdentificationDBManager.getCodeMatchPreparedStatement(projectName);
    String fileName = null;// www .  j a va 2s  . c  om
    String component = null;
    String version = null;
    String license = null;
    int usage = 0;
    String status = null;
    String percentage = null;
    int percentageNumber = 0;
    String matchedFile = null;
    String fileComment = null;

    if (list == null) {
        System.err.println("Not Founded CodeMatches PendingIdentification Precision.");
    } else {
        for (CodeMatchesPrecision tmpPendingFile : list) {
            fileName = tmpPendingFile.getFile();
            component = tmpPendingFile.getComponent();
            version = tmpPendingFile.getVersion();
            if (version == null)
                version = "";
            license = tmpPendingFile.getLicense();
            usage = (tmpPendingFile.getUsage().equals("File")) ? CodeMatchInfo.USAGE_FILE
                    : CodeMatchInfo.USAGE_SNIPPET;
            status = tmpPendingFile.getStatus();
            percentage = tmpPendingFile.getPercentage();
            percentageNumber = Tools.transStringToInteger(percentage.substring(0, percentage.length() - 1));
            matchedFile = tmpPendingFile.getMatchedFile();
            fileComment = tmpPendingFile.getFileComment();
            fileComment = fileComment.replace("<br />", "\n");

            try {
                prepCodematchTable.setString(1, fileName);
                prepCodematchTable.setString(2, component);
                prepCodematchTable.setString(3, version);
                prepCodematchTable.setString(4, license);
                prepCodematchTable.setString(5, String.valueOf(usage));
                if (status.startsWith("Precision Match")) {
                    prepCodematchTable.setString(6, String.valueOf(AbstractMatchInfo.STATUS_PENDING));
                } else if (status.startsWith("Identified")) {
                    prepCodematchTable.setString(6, String.valueOf(AbstractMatchInfo.STATUS_IDENTIFIED));
                } else if (status.startsWith("Identified by Generic Version")) {
                    prepCodematchTable.setString(6, String.valueOf(AbstractMatchInfo.STATUS_REJECT));
                } else if (status.startsWith("Rejected")) {
                    prepCodematchTable.setString(6, String.valueOf(AbstractMatchInfo.STATUS_REJECT));
                } else if (status.startsWith("Declared")) {
                    prepCodematchTable.setString(6, String.valueOf(AbstractMatchInfo.STATUS_DECLARED));
                }
                prepCodematchTable.setInt(7, percentageNumber);
                prepCodematchTable.setString(8, matchedFile);
                prepCodematchTable.setString(9, fileComment);
                prepCodematchTable.addBatch();
            } catch (SQLException e) {
                ReportAPIWrapper.log.warn(e);
            }
        }
        IdentificationDBManager.execute(prepCodematchTable);
        if (prepCodematchTable != null) {
            try {
                prepCodematchTable.close();
            } catch (SQLException e) {
                ReportAPIWrapper.log.warn(e);
            }
        }
    }
}

From source file:org.wso2.carbon.identity.oauth2.dao.AuthorizationCodeDAOImpl.java

@Override
public void deactivateAuthorizationCodes(List<AuthzCodeDO> authzCodeDOs) throws IdentityOAuth2Exception {

    Connection connection = IdentityDatabaseUtil.getDBConnection();
    PreparedStatement prepStmt = null;

    if (log.isDebugEnabled()) {
        if (IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.AUTHORIZATION_CODE)) {
            StringBuilder stringBuilder = new StringBuilder();
            for (AuthzCodeDO authzCodeDO : authzCodeDOs) {
                stringBuilder.append("Deactivating authorization code(hashed): ")
                        .append(DigestUtils.sha256Hex(authzCodeDO.getAuthorizationCode())).append(" client: ")
                        .append(authzCodeDO.getConsumerKey()).append(" user: ")
                        .append(authzCodeDO.getAuthorizedUser().toString()).append("\n");
            }//w  w w  .j  a v a 2s  .  c om
            log.debug(stringBuilder.toString());
        } else {
            StringBuilder stringBuilder = new StringBuilder();
            for (AuthzCodeDO authzCodeDO : authzCodeDOs) {
                stringBuilder.append("Deactivating authorization code client: ")
                        .append(authzCodeDO.getConsumerKey()).append(" user: ")
                        .append(authzCodeDO.getAuthorizedUser().toString()).append("\n");
            }
            log.debug(stringBuilder.toString());
        }
    }
    try {
        prepStmt = connection.prepareStatement(SQLQueries.DEACTIVATE_AUTHZ_CODE_AND_INSERT_CURRENT_TOKEN);
        for (AuthzCodeDO authzCodeDO : authzCodeDOs) {
            prepStmt.setString(1, authzCodeDO.getOauthTokenId());
            prepStmt.setString(2,
                    getHashingPersistenceProcessor().getProcessedAuthzCode(authzCodeDO.getAuthorizationCode()));
            prepStmt.addBatch();
        }
        prepStmt.executeBatch();
        connection.commit();

        // To revoke request objects which are persisted against the code.
        OAuth2TokenUtil.postRevokeCodes(authzCodeDOs, OAuthConstants.AuthorizationCodeState.INACTIVE);
    } catch (SQLException e) {
        throw new IdentityOAuth2Exception("Error when deactivating authorization code", e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, null, prepStmt);
    }
}

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

public void testBatchUpdateWithPreparedStatement() 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();
    ctrlPreparedStatement.setVoidCallable();
    mockPreparedStatement.setInt(1, ids[1]);
    ctrlPreparedStatement.setVoidCallable();
    mockPreparedStatement.addBatch();/*from w  ww.java  2 s. co m*/
    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 BatchPreparedStatementSetter() {
        public void setValues(PreparedStatement ps, int i) throws SQLException {
            ps.setInt(1, ids[i]);
        }

        public int getBatchSize() {
            return 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:org.springframework.jdbc.core.JdbcTemplateTests.java

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

    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();
    ctrlPreparedStatement.setVoidCallable();
    mockPreparedStatement.setInt(1, ids[1]);
    ctrlPreparedStatement.setVoidCallable();
    mockPreparedStatement.addBatch();//  w  w w  . j a  va  2 s  .  c om
    ctrlPreparedStatement.setVoidCallable();
    mockPreparedStatement.executeBatch();
    ctrlPreparedStatement.setThrowable(sex);
    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);

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

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

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

        public int getBatchSize() {
            return ids.length;
        }
    };

    try {
        JdbcTemplate template = new JdbcTemplate(mockDataSource);
        template.batchUpdate(sql, setter);
        fail("Should have failed because of SQLException in bulk update");
    } catch (DataAccessException ex) {
        assertTrue("Root cause is SQLException", ex.getCause() == sex);
    }

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

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

public void testInterruptibleBatchUpdateWithBaseClass() 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();
    ctrlPreparedStatement.setVoidCallable();
    mockPreparedStatement.setInt(1, ids[1]);
    ctrlPreparedStatement.setVoidCallable();
    mockPreparedStatement.addBatch();//from  w ww.  java 2s  . c om
    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 AbstractInterruptibleBatchPreparedStatementSetter() {
        protected boolean setValuesIfAvailable(PreparedStatement ps, int i) throws SQLException {
            if (i < ids.length) {
                ps.setInt(1, ids[i]);
                return true;
            } else {
                return false;
            }
        }
    };

    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: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();
    ctrlPreparedStatement.setVoidCallable();
    mockPreparedStatement.setInt(1, ids[1]);
    ctrlPreparedStatement.setVoidCallable();
    mockPreparedStatement.addBatch();//from  ww w .  j ava  2  s.c om
    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:com.appspot.relaxe.tools.CSVInsertTask.java

public void run(Connection connection, Reader input, Table table) throws IOException, SQLException {

    if (connection == null) {
        throw new NullPointerException("'connection' must not be null");
    }//from   w  w  w  . j a  va  2  s.c  o m

    if (input == null) {
        throw new NullPointerException("'input' must not be null");
    }

    if (table == null) {
        throw new NullPointerException("'table' must not be null");
    }

    boolean committed = false;

    try {
        connection.setAutoCommit(false);
        CSVStrategy cs = new CSVStrategy('\t', '"', CSVStrategy.COMMENTS_DISABLED, false, false, false);
        CSVParser p = new CSVParser(input, cs);

        // get header line
        String[] line = p.getLine();

        // configure by using the column headers:        
        ColumnMap cm = table.getColumnMap();
        List<Identifier> names = new ArrayList<Identifier>();
        List<Column> columnList = new ArrayList<Column>();

        for (String n : line) {
            Column column = cm.get(n);

            if (column == null) {
                throw new IllegalArgumentException("column not found " + n);
            }

            columnList.add(column);
            names.add(column.getColumnName());
        }

        if (names.isEmpty()) {
            throw new IllegalStateException("no column names available");
        }

        ElementList<Identifier> nel = ElementList.newElementList(names);

        final int expectedColumnCount = line.length;
        //            int recno = 0;        

        PreparedStatement ps = null;
        InsertStatement ins = null;

        VarcharParameter[] params = new VarcharParameter[expectedColumnCount];
        ValueAssignerFactory vaf = getImplementation().getValueAssignerFactory();

        AssignmentVisitor pa = null;

        while ((line = p.getLine()) != null) {
            //                recno++;
            final int cols = line.length;
            int lineno = p.getLineNumber();

            if (cols != expectedColumnCount) {
                throw new IllegalStateException("unexpected column count: " + cols + " at line " + lineno);
            }

            if (ps == null) {

                List<RowValueConstructorElement> vl = new ArrayList<RowValueConstructorElement>(params.length);

                for (int i = 0; i < params.length; i++) {
                    Column column = columnList.get(i);
                    VarcharHolder h = parse(column, line[i]);

                    VarcharParameter param = new VarcharParameter(column, h);
                    params[i] = param;
                    vl.add(param);
                }

                RowValueConstructor rvc = AbstractRowValueConstructor.of(vl);
                ins = new InsertStatement(table, nel, rvc);

                String q = ins.generate();
                ps = connection.prepareStatement(q);
                pa = new AssignmentVisitor(vaf, ps);

                //                System.err.println("lineno: " + lineno);
                //                System.err.println("record: " + recno);
                //                System.err.println("query: " + q);
            } else {
                pa.reset();

                for (int i = 0; i < line.length; i++) {
                    Column column = columnList.get(i);
                    VarcharHolder h = parse(column, line[i]);
                    VarcharParameter param = params[i];
                    param.setValue(h);
                }
            }

            ins.traverse(null, pa);
            ps.addBatch();
        }

        int[] updateCounts = ps.executeBatch();
        updated(updateCounts);
        connection.commit();
        committed = true;
    } finally {
        if (!(committed)) {
            QueryHelper.doRollback(connection);
        }
    }
}