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:com.tera.common.database.query.CQueryService.java

@Override
public <T> boolean batchUpdate(String batchUpdate, BatchUpdateQuery<T> query, String errorMessage,
        boolean autoCommit) {
    Connection connection = null;
    PreparedStatement statement = null;

    try {/*from w  ww.  j a  va2s.  c  o  m*/
        connection = databaseFactory.getConnection();
        statement = connection.prepareStatement(batchUpdate);
        connection.setAutoCommit(autoCommit);

        Collection<T> items = query.getItems();
        for (T item : items) {
            query.handleBatch(statement, item);
            statement.addBatch();
        }
        statement.executeBatch();

        if (!autoCommit) {
            connection.commit();
        }
    } catch (Exception e) {
        if (errorMessage == null)
            log.error("Failed to execute BatchUpdate query {}", e, e);
        else
            log.error(errorMessage + " " + e, e);
        return false;
    } finally {

        close(null, statement, connection);
    }
    return true;
}

From source file:org.bytesoft.bytejta.supports.jdbc.RecoveredResource.java

public synchronized void forget(Xid[] xids) throws XAException {
    if (xids == null || xids.length == 0) {
        return;//from  ww  w .j  a  v  a 2 s . com
    }

    String[] xidArray = new String[xids.length];

    for (int i = 0; i < xids.length; i++) {
        Xid xid = xids[i];

        byte[] globalTransactionId = xid.getGlobalTransactionId();
        byte[] branchQualifier = xid.getBranchQualifier();
        xidArray[i] = this.getIdentifier(globalTransactionId, branchQualifier);
    }

    Connection conn = null;
    PreparedStatement stmt = null;
    Boolean autoCommit = null;
    try {
        conn = this.dataSource.getConnection();
        autoCommit = conn.getAutoCommit();
        conn.setAutoCommit(false);
        stmt = conn.prepareStatement("delete from bytejta where xid = ?");
        for (int i = 0; i < xids.length; i++) {
            stmt.setString(1, xidArray[i]);
            stmt.addBatch();
        }
        stmt.executeBatch();
        conn.commit();
    } catch (Exception ex) {
        logger.error("Error occurred while forgetting resources.");

        try {
            conn.rollback();
        } catch (Exception sqlEx) {
            logger.error("Error occurred while rolling back local resources.", sqlEx);
        }

        boolean tableExists = false;
        try {
            tableExists = this.isTableExists(conn);
        } catch (Exception sqlEx) {
            logger.warn("Error occurred while forgeting local resources.", ex);
            throw new XAException(XAException.XAER_RMFAIL);
        }

        if (tableExists) {
            throw new XAException(XAException.XAER_RMERR);
        }
    } finally {
        if (autoCommit != null) {
            try {
                conn.setAutoCommit(autoCommit);
            } catch (SQLException sqlEx) {
                logger.error("Error occurred while configuring attribute 'autoCommit'.", sqlEx);
            }
        }

        this.closeQuietly(stmt);
        this.closeQuietly(conn);
    }
}

From source file:com.splicemachine.derby.impl.sql.execute.operations.InsertOperationIT.java

@Test
public void testBatchInsert() throws Exception {
    Connection conn = methodWatcher.getOrCreateConnection();
    //insert a single record
    conn.setAutoCommit(false);/*from ww  w .  j a v  a  2s .  co m*/
    PreparedStatement ps = conn.prepareStatement("insert into batch_test (col1,col2,col3) values (?,?,?)");
    int iterCount = 10;
    for (int i = 0; i < iterCount; i++) {
        ps.setInt(1, i);
        ps.setInt(2, i);
        ps.setInt(3, i);
        ps.addBatch();
    }
    int[] results = ps.executeBatch();
    Assert.assertEquals("results returned correct", 10, results.length);
    ps.close();
    ps = conn.prepareStatement("select count(*) from batch_test");
    ResultSet rs = ps.executeQuery();
    rs.next();
    Assert.assertEquals("results returned correct", 10, rs.getInt(1));
}

From source file:org.rhq.enterprise.server.purge.PurgeTemplate.java

private int deleteRows(List<KEY> selectedKeys) throws Exception {
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    try {/*  www.  ja va2s.  c  o  m*/

        userTransaction.begin();

        String deleteRowByKeyQuery = getDeleteRowByKeyQuery(databaseType);

        connection = dataSource.getConnection();
        preparedStatement = connection.prepareStatement(deleteRowByKeyQuery);

        for (KEY key : selectedKeys) {
            setDeleteRowByKeyQueryParams(preparedStatement, key);
            preparedStatement.addBatch();
        }

        int[] batchResults = preparedStatement.executeBatch();

        userTransaction.commit();

        return evalDeletedRows(batchResults);

    } finally {
        JDBCUtil.safeClose(connection, preparedStatement, null);
        rollbackIfTransactionActive();
    }
}

From source file:org.seasar.dbflute.s2dao.sqlhandler.TnAbstractBasicSqlHandler.java

protected void addBatch(PreparedStatement ps) {
    try {// w  w  w .java  2s .c  o m
        ps.addBatch();
    } catch (SQLException e) {
        handleSQLException(e, ps);
    }
}

From source file:org.apache.sqoop.mapreduce.SQLServerUpdateDBExecThread.java

/**
 * Generate the PreparedStatement object that will be used to update records
 * in the database. All parameterized fields of the PreparedStatement must
 * be set in this method as well; this is usually based on the records
 * collected from the user in the records list
 *
 * This method must be overridden by sub-classes to define the database
 * operation to be executed for user records
 *//*from   w w w. ja va2 s . c o  m*/
@Override
protected PreparedStatement getPreparedStatement(List<SqoopRecord> records) throws SQLException {
    PreparedStatement stmt = null;
    Connection conn = getConnection();

    // Create a PreparedStatement object to Update all records
    stmt = conn.prepareStatement(getUpdateStatement());

    // Inject the record parameters into the UPDATE and WHERE clauses.  This
    // assumes that the update key column is the last column serialized in
    // by the underlying record. Our code auto-gen process for exports was
    // responsible for taking care of this constraint.
    for (SqoopRecord record : records) {
        record.write(stmt, 0);
        stmt.addBatch();
    }

    return stmt;
}

From source file:eionet.cr.dao.virtuoso.VirtuosoUrgentHarvestQueueDAO.java

@Override
public void addPullHarvests(List<UrgentHarvestQueueItemDTO> queueItems) throws DAOException {

    String sql = "insert into URGENT_HARVEST_QUEUE (URL,\"TIMESTAMP\") VALUES (?,NOW())";
    PreparedStatement ps = null;
    Connection conn = null;/*from  ww w.  j a va 2  s  . c o  m*/
    try {
        conn = getSQLConnection();
        ps = conn.prepareStatement(sql);
        for (int i = 0; i < queueItems.size(); i++) {
            UrgentHarvestQueueItemDTO dto = queueItems.get(i);
            String url = dto.getUrl();
            if (url != null) {
                url = StringUtils.substringBefore(url, "#");
            }
            ps.setString(1, url);
            ps.addBatch();
        }
        ps.executeBatch();
    } catch (Exception e) {
        throw new DAOException(e.getMessage(), e);
    } finally {
        SQLUtil.close(ps);
        SQLUtil.close(conn);
    }
}

From source file:org.wso2.carbon.device.mgt.core.dao.impl.ApplicationMappingDAOImpl.java

@Override
public void addApplicationMappings(int deviceId, List<Integer> applicationIds, int tenantId)
        throws DeviceManagementDAOException {
    Connection conn;//from w  w  w .  java  2s . co  m
    PreparedStatement stmt = null;
    ResultSet rs = null;

    try {
        conn = this.getConnection();
        String sql = "INSERT INTO DM_DEVICE_APPLICATION_MAPPING (DEVICE_ID, APPLICATION_ID, "
                + "TENANT_ID) VALUES (?, ?, ?)";

        conn.setAutoCommit(false);
        stmt = conn.prepareStatement(sql);

        for (int applicationId : applicationIds) {
            stmt.setInt(1, deviceId);
            stmt.setInt(2, applicationId);
            stmt.setInt(3, tenantId);
            stmt.addBatch();
        }
        stmt.executeBatch();
    } catch (SQLException e) {
        throw new DeviceManagementDAOException("Error occurred while adding device application mappings", e);
    } finally {
        DeviceManagementDAOUtil.cleanupResources(stmt, rs);
    }
}

From source file:eionet.cr.dao.virtuoso.VirtuosoEndpointHarvestQueryDAO.java

@Override
public void delete(List<Integer> ids) throws DAOException {

    if (ids == null || ids.isEmpty()) {
        return;// w  ww .j a  v a  2  s.  c om
    }

    Connection conn = null;
    PreparedStatement stmt = null;
    try {
        conn = getSQLConnection();
        conn.setAutoCommit(false);
        stmt = conn.prepareStatement(DELETE_SQL);
        for (Integer id : ids) {
            stmt.setInt(1, id);
            stmt.addBatch();
        }
        stmt.executeBatch();
        conn.commit();
    } catch (SQLException e) {
        SQLUtil.rollback(conn);
        throw new DAOException(e.getMessage(), e);
    } finally {
        SQLUtil.close(stmt);
        SQLUtil.close(conn);
    }
}

From source file:com.dsf.dbxtract.cdc.journal.JournalExecutor.java

/**
 * Removes imported references from journal table.
 * /*  w  ww .ja v  a  2 s .  c o m*/
 * @param conn
 * @param rows
 * @throws SQLException
 */
private void deleteFromJournal(Connection conn, List<Map<String, Object>> rows) throws SQLException {

    if (rows.isEmpty()) {
        if (logger.isDebugEnabled())
            logger.debug(logPrefix + "nothing to clean");
        return;
    }

    if (logger.isDebugEnabled())
        logger.debug(logPrefix + "cleaning journal " + handler.getJournalTable());

    StringBuilder sb = new StringBuilder("delete from " + handler.getJournalTable() + " where ");
    for (int i = 0; i < journalColumns.size(); i++) {
        sb.append(i > 0 ? " and " : "").append(journalColumns.get(i)).append("=?");
    }
    PreparedStatement ps = null;
    try {
        ps = conn.prepareStatement(sb.toString());
        for (Map<String, Object> keys : rows) {
            for (int i = 0; i < journalColumns.size(); i++) {
                ps.setObject(i + 1, keys.get(journalColumns.get(i)));
            }
            ps.addBatch();
        }
        ps.executeBatch();
        logger.info(logPrefix + rows.size() + " rows removed (" + handler.getJournalTable() + ")");

    } finally {
        DBUtils.close(ps);
    }
}