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.taobao.tddl.jdbc.group.TGroupPreparedStatement.java

private int[] executeBatchOnConnection(Connection conn) throws SQLException {
    PreparedStatement ps = createPreparedStatementInternal(conn, sql);

    for (Map<Integer, ParameterContext> parameterSettings : pstArgs) {
        setBatchParameters(ps, parameterSettings.values());
        ps.addBatch();
    }//from www.j  av a  2s  . c o m

    return ps.executeBatch();
}

From source file:org.schedoscope.metascope.tasks.repository.mysql.impl.TableEntityMySQLRepository.java

public void updateStatus(Connection connection, Set<TableEntity> tables) {
    String updateStatus = "update table_entity set status=?, last_transformation_timestamp=? where table_fqdn = ?";
    PreparedStatement updateStatusStmt = null;
    try {//from   w  ww  . j  av  a2 s.  c  o m
        int updateStatusBatch = 0;
        connection.setAutoCommit(false);
        updateStatusStmt = connection.prepareStatement(updateStatus);
        for (TableEntity tableEntity : tables) {
            updateStatusStmt.setString(1, tableEntity.getStatus());
            updateStatusStmt.setLong(2, tableEntity.getLastTransformation());
            updateStatusStmt.setString(3, tableEntity.getFqdn());
            updateStatusStmt.addBatch();
            updateStatusBatch++;
            if (updateStatusBatch % 1000 == 0) {
                updateStatusStmt.executeBatch();
            }
        }
        updateStatusStmt.executeBatch();
        connection.commit();
        connection.setAutoCommit(true);
    } catch (SQLException e) {
        LOG.error("Could not update table", e);
    } finally {
        DbUtils.closeQuietly(updateStatusStmt);
    }
}

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

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

    if (ids == null || ids.isEmpty()) {
        return;/*w ww. j a v a2  s  .  com*/
    }

    Connection conn = null;
    PreparedStatement stmt = null;
    try {
        conn = getSQLConnection();
        conn.setAutoCommit(false);
        stmt = conn.prepareStatement(ACTIVATE_DEACTIVATE_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.nabla.dc.server.xml.settings.XmlUser.java

public boolean save(final Connection conn, final SaveContext ctx) throws SQLException, DispatchException {
    Integer userId = ctx.getUserIds().get(getName());
    if (userId != null) {
        if (ctx.getOption() == SqlInsertOptions.APPEND) {
            if (log.isDebugEnabled())
                log.debug("skipping user '" + getName() + "' (already defined)");
            return true;
        }/*from w  w  w .  j a  va 2  s .  c  om*/
        Database.executeUpdate(conn, "UPDATE user SET password=?,active=? WHERE id=?;",
                UserManager.getPasswordEncryptor().encryptPassword(password.getValue()), active, userId);
        Database.executeUpdate(conn, "DELETE FROM user_definition WHERE object_id IS NULL AND user_id=?;",
                userId);
    } else {
        if (log.isDebugEnabled())
            log.debug("adding user '" + getName() + "'");
        userId = Database.addRecord(conn, "INSERT INTO user (name,uname,active,password) VALUES(?,?,?,?);",
                getName(), getName().toUpperCase(), active,
                UserManager.getPasswordEncryptor().encryptPassword(password.getValue()));
        if (userId == null)
            throw new InternalErrorException(Util.formatInternalErrorDescription("failed to insert user"));
        ctx.getUserIds().put(getName(), userId);
    }
    if (roles == null || roles.isEmpty())
        return true;
    if (log.isDebugEnabled())
        log.debug("saving user definition for '" + getName() + "'");
    final IErrorList<Integer> errors = ctx.getErrorList();
    final PreparedStatement stmt = conn
            .prepareStatement("INSERT INTO user_definition (user_id, role_id) VALUES(?,?);");
    try {
        stmt.setInt(1, userId);
        boolean success = true;
        for (XmlRoleName role : roles) {
            final Integer id = ctx.getRoleIds().get(role.getValue());
            if (id == null) {
                errors.add(role.getRow(), XmlRoleName.FIELD, CommonServerErrors.INVALID_VALUE);
                success = false;
            } else {
                stmt.setInt(2, id);
                stmt.addBatch();
            }
        }
        if (success && !Database.isBatchCompleted(stmt.executeBatch()))
            throw new InternalErrorException(
                    Util.formatInternalErrorDescription("failed to insert user definition"));
        return success;
    } finally {
        Database.close(stmt);
    }
}

From source file:org.openmrs.util.databasechange.UpdateCohortMemberIds.java

/**
 * @see CustomTaskChange#execute(Database)
 *///  w  w w.j  a va  2 s  . c o  m
@Override
public void execute(Database database) throws CustomChangeException {
    JdbcConnection connection = (JdbcConnection) database.getConnection();
    Statement stmt = null;
    PreparedStatement pStmt = null;

    try {
        stmt = connection.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM cohort_member");

        pStmt = connection.prepareStatement(
                "UPDATE cohort_member SET cohort_member_id = ?" + " WHERE cohort_id = ? AND patient_id = ?");
        int i = 0;
        while (rs.next()) {
            int cohortId = rs.getInt("cohort_id");
            int patientId = rs.getInt("patient_id");
            pStmt.setInt(1, ++i);
            pStmt.setInt(2, cohortId);
            pStmt.setInt(3, patientId);
            pStmt.addBatch();
        }
        pStmt.executeBatch();
    } catch (DatabaseException | SQLException e) {
        log.warn("Error generated", e);
    } finally {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                log.warn("Failed to close the statement object");
            }
        }

        if (pStmt != null) {
            try {
                pStmt.close();
            } catch (SQLException e) {
                log.warn("Failed to close the prepared statement object");
            }
        }
    }
}

From source file:iddb.runtime.db.model.dao.impl.mysql.PenaltyDAOImpl.java

@Override
public void delete(List<Penalty> list) {
    String sql = "delete from penalty where id = ?";
    Connection conn = null;/*from   ww w  . j a va 2  s  . co  m*/
    try {
        conn = ConnectionFactory.getMasterConnection();
        PreparedStatement st = conn.prepareStatement(sql);
        for (Penalty p : list) {
            st.setLong(1, p.getKey());
            st.addBatch();
        }
        st.executeBatch();
    } catch (SQLException e) {
        logger.error("delete: {}", e);
    } catch (IOException e) {
        logger.error("delete: {}", e);
    } finally {
        try {
            if (conn != null)
                conn.close();
        } catch (Exception e) {
        }
    }
}

From source file:org.schedoscope.metascope.tasks.repository.mysql.impl.FieldEntityMySQLRepository.java

@Override
public void insertOrUpdate(Connection connection, List<FieldEntity> fields) {
    String insertFieldSql = "insert into field_entity ("
            + JDBCUtil.getDatabaseColumnsForClass(FieldEntity.class) + ") values ("
            + JDBCUtil.getValuesCountForClass(FieldEntity.class) + ") " + "on duplicate key update "
            + MySQLUtil.getOnDuplicateKeyString(FieldEntity.class);
    PreparedStatement stmt = null;
    try {/*from w  w w .j  ava  2  s  .c  om*/
        int batch = 0;
        connection.setAutoCommit(false);
        stmt = connection.prepareStatement(insertFieldSql);
        for (FieldEntity fieldEntity : fields) {
            stmt.setString(1, fieldEntity.getFqdn());
            stmt.setString(2, fieldEntity.getName());
            stmt.setString(3, fieldEntity.getType());
            stmt.setString(4, fieldEntity.getDescription());
            stmt.setInt(5, fieldEntity.getFieldOrder());
            stmt.setBoolean(6, fieldEntity.isParameterField());
            stmt.setString(7, fieldEntity.getFqdn());
            stmt.addBatch();
            batch++;
            if (batch % 1024 == 0) {
                stmt.executeBatch();
            }
        }
        stmt.executeBatch();
        connection.commit();
        connection.setAutoCommit(true);
    } catch (SQLException e) {
        LOG.error("Could not save field", e);
    } finally {
        DbUtils.closeQuietly(stmt);
    }
}

From source file:com.nabla.dc.server.xml.settings.XmlRole.java

public boolean save(final Connection conn, final SaveContext ctx) throws SQLException, DispatchException {
    final IErrorList<Integer> errors = ctx.getErrorList();
    if (ctx.getPrivilegeIds().containsKey(getName())) {
        if (log.isDebugEnabled())
            log.debug("role '" + getName() + "' is already defined as a privilege");
        errors.add(name.getRow(), "name", CommonServerErrors.DUPLICATE_ENTRY);
        return false;
    }/*from w  ww.j av a2 s . c om*/
    Integer roleId = ctx.getRoleIds().get(getName());
    if (roleId != null) {
        if (ctx.getOption() == SqlInsertOptions.APPEND) {
            if (log.isDebugEnabled())
                log.debug("skipping role '" + getName() + "' (already defined)");
            return true;
        }
        // nothing to update for the actual role record
        // but clear definition before replacing it with new definition
        Database.executeUpdate(conn, "DELETE FROM role_definition WHERE role_id=?;", roleId);
    } else {
        if (log.isDebugEnabled())
            log.debug("adding role '" + getName() + "'");
        roleId = Database.addRecord(conn, "INSERT INTO role (name,uname) VALUES(?,?);", getName(),
                getName().toUpperCase());
        if (roleId == null)
            throw new InternalErrorException(
                    Util.formatInternalErrorDescription("failed to insert role '" + getName() + "'"));
        ctx.getRoleIds().put(getName(), roleId);
    }
    if (definition == null || definition.isEmpty())
        return true;
    if (log.isDebugEnabled())
        log.debug("saving role definition for '" + getName() + "'");
    final PreparedStatement stmt = conn
            .prepareStatement("INSERT INTO role_definition (role_id, child_role_id) VALUES(?,?);");
    try {
        stmt.setInt(1, roleId);
        boolean success = true;
        for (XmlRoleName role : definition) {
            final Integer id = ctx.getRoleIds().get(role.getValue());
            if (id == null) {
                errors.add(role.getRow(), XmlRoleName.FIELD, CommonServerErrors.INVALID_VALUE);
                success = false;
            } else {
                stmt.setInt(2, id);
                stmt.addBatch();
            }
        }
        if (success && !Database.isBatchCompleted(stmt.executeBatch()))
            throw new InternalErrorException(
                    Util.formatInternalErrorDescription("failed to insert role definition"));
        return success;
    } finally {
        Database.close(stmt);
    }
}

From source file:org.openmrs.util.databasechange.UpdateLayoutAddressFormatChangeSet.java

/**
 * @see CustomTaskChange#execute(Database)
 *///w  w  w.j a  va2s.c  o  m
@Override
public void execute(Database database) throws CustomChangeException {
    JdbcConnection connection = (JdbcConnection) database.getConnection();
    Statement stmt = null;
    PreparedStatement pStmt = null;

    try {
        stmt = connection.createStatement();
        ResultSet rs = stmt.executeQuery(
                "SELECT property_value FROM global_property WHERE property = 'layout.address.format'");
        if (rs.next()) {
            String value = rs.getString("property_value");
            value = value.replace("org.openmrs.layout.web.", "org.openmrs.layout.");

            pStmt = connection.prepareStatement(
                    "UPDATE global_property SET property_value = ? WHERE property = 'layout.address.format'");
            pStmt.setString(1, value);
            pStmt.addBatch();
            pStmt.executeBatch();
        }
    } catch (DatabaseException e) {
        log.warn("Error generated", e);
    } catch (SQLException e) {
        log.warn("Error generated", e);
    } finally {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                log.warn("Failed to close the statement object");
            }
        }

        if (pStmt != null) {
            try {
                pStmt.close();
            } catch (SQLException e) {
                log.warn("Failed to close the prepared statement object");
            }
        }
    }
}

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

@Override
public void truncateOperationIDsForArchival() throws ArchivalDAOException {
    PreparedStatement stmt = null;
    try {//from ww w . j a va  2s . c  o m
        Connection conn = ArchivalSourceDAOFactory.getConnection();
        conn.setAutoCommit(false);
        String sql = "TRUNCATE DM_ARCHIVED_OPERATIONS";
        stmt = conn.prepareStatement(sql);
        stmt.addBatch();
        stmt.executeBatch();
        conn.commit();
    } catch (SQLException e) {
        throw new ArchivalDAOException("Error occurred while truncating operation Ids", e);
    } finally {
        ArchivalDAOUtil.cleanupResources(stmt);
    }
}