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:org.openbel.framework.core.kam.JdbcKAMLoaderImpl.java

/**
 * {@inheritDoc}/*from   www. j  a va 2 s.  c o  m*/
 */
@Override
public void loadAnnotationDefinitionTypes() throws SQLException {
    int adtid = 0;

    PreparedStatement ps = getPreparedStatement(ANNOTATION_DEFINITION_TYPE_SQL);
    for (AnnotationType at : AnnotationType.values()) {
        String annotationTypeName = at.getDisplayValue();
        ps.setInt(1, adtid);
        ps.setString(2, annotationTypeName);
        ps.addBatch();
        adtid++;
    }

    // FIXME [Hack] add URL annotation type
    ps.setInt(1, AnnotationDefinitionTable.URL_ANNOTATION_TYPE_ID);
    ps.setString(2, AnnotationDefinitionTable.URL_ANNOTATION_TYPE);
    ps.addBatch();

    ps.executeBatch();
}

From source file:org.openbel.framework.core.kam.JdbcKAMLoaderImpl.java

/**
 * {@inheritDoc}//from  www. j  a  v a 2  s . co  m
 */
@Override
public Map<String, Integer> loadObjectTypes() throws SQLException {
    int otid = 0;

    PreparedStatement ps = getPreparedStatement(OBJECT_TYPE_SQL);

    Map<String, Integer> objectTypeIdMap = new HashMap<String, Integer>();
    ps.setInt(1, otid);
    ps.setString(2, "number");
    ps.addBatch();
    objectTypeIdMap.put("number", otid);
    otid++;
    ps.setInt(1, otid);
    ps.setString(2, "varchar");
    ps.addBatch();
    objectTypeIdMap.put("varchar", otid);
    otid++;
    ps.setInt(1, otid);
    ps.setString(2, "clob");
    ps.addBatch();
    objectTypeIdMap.put("clob", otid);

    ps.executeBatch();
    return objectTypeIdMap;
}

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

public void insert(String parentId, InternationalStringType is) throws RegistryException {
    PreparedStatement pstmt = null;

    try {/* w w  w.j ava 2 s . co  m*/
        String str = "INSERT INTO " + getTableName() + " VALUES(?, " + // charsetName
                "?," + // lang
                "?, " + // value
                "?)"; // parentId
        pstmt = context.getConnection().prepareStatement(str);

        if (is != null) {
            Iterator lsItems = is.getLocalizedString().iterator();

            while (lsItems.hasNext()) {
                LocalizedString ls = (LocalizedString) lsItems.next();
                String charset = ls.getCharset();
                String lang = ls.getLang();
                String value = ls.getValue();
                String charsetName = ls.getCharset();

                if (value != null && value.length() > 0) {
                    pstmt.setString(1, charsetName);
                    pstmt.setString(2, lang);
                    pstmt.setString(3, value);
                    pstmt.setString(4, parentId);
                    log.trace("SQL = " + str); // HIEOS/BHT: DEBUG (fix)
                    pstmt.addBatch();
                }
            }
        }

        if (is != null) {
            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:org.openbel.framework.core.kam.JdbcKAMLoaderImpl.java

/**
 * {@inheritDoc}/*from  ww w  . j a  v  a 2 s .c  o m*/
 */
@Override
public void loadStatementAnnotationMap(StatementAnnotationMapTable samt) throws SQLException {
    Map<Integer, Set<AnnotationPair>> sidAnnotationIndex = samt.getStatementAnnotationPairsIndex();

    PreparedStatement saps = getPreparedStatement(STATEMENT_ANNOTATION_SQL);

    final Set<Entry<Integer, Set<AnnotationPair>>> entries = sidAnnotationIndex.entrySet();
    for (final Entry<Integer, Set<AnnotationPair>> entry : entries) {
        final Integer sid = entry.getKey();
        for (final AnnotationPair annotation : entry.getValue()) {
            // XXX offset
            saps.setInt(1, sid + 1);
            // XXX offset
            saps.setInt(2, annotation.getAnnotationValueId() + 1);
            saps.addBatch();
        }
    }
    saps.executeBatch();
}

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

@SuppressWarnings("unused")
private void up1991To1992() throws Exception {
    log.info("Version 1.991 to 1.992 is upgarding");
    String root = DataRoot.getDataRoot();
    if (FileUtil.exist(root + Server.FILE)) {
        Server server = new Server();
        Properties prop = FileUtil.loadProperties(root + Server.FILE);
        server.syncFrom(prop);/*from  w  ww.ja v a 2  s.c  o m*/
        String type = server.getDbType();

        DBLoader loader = new DBLoader();
        ConnectionProxy con = loader.getConnection(type, server.getDbUrl(), server.getDbSchema(),
                server.getDbUsername(), server.getDbPassword());

        Statement stat = con.createStatement();
        ResultSet rs0 = stat.executeQuery("select PUID from EDG_ROLES where NAME='ROLE_SYS_USERS'");
        if (rs0.next()) {
            int roleID = rs0.getInt(1);
            rs0.close();

            PreparedStatement pre0 = con.prepareStatement(
                    "select distinct USER_PUID from EDG_USER_ROLE where USER_PUID in (select PUID from EDG_USERS where PUID not in "
                            + " (select u.PUID from EDG_USERS as u, EDG_USER_ROLE as r where u.PUID=r.USER_PUID and r.ROLE_PUID=?))");
            pre0.setInt(1, roleID);
            ResultSet rs1 = pre0.executeQuery();

            PreparedStatement pre = con
                    .prepareStatement("insert into EDG_USER_ROLE(USER_PUID,ROLE_PUID) values(?,?)");
            while (rs1.next()) {
                pre.setInt(1, rs1.getInt(1));
                pre.setInt(2, roleID);
                pre.addBatch();
            }
            pre.executeBatch();

            rs1.close();
            pre0.close();
            pre.close();
        }
        stat.close();
        con.close();
    }
}

From source file:ccc.cli.StringToDecConverterUtil.java

/**
 * Generates and stores decimal values for the values of the paragraphs
 * of type 'NUMBER'. The new values are stored in the value_decimal column.
        /*w w w .j  a v  a  2s . co  m*/
 * @param connection The DB connection.
 */
public void convertParagraphs(final Connection connection) {
    LOG.info("Convert Paragraphs Started");
    Statement stmt = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;

    try {

        stmt = connection.createStatement();
        LOG.trace("Getting the paragraphs where type is 'NUMBER'");
        rs = stmt.executeQuery(GET_PARAGRAPHS_QUERY);

        if (rs != null && rs.next()) {
            LOG.debug("Processing result set");
            pstmt = connection.prepareStatement(UPDATE_PARAGRAPH);
            int totalparagraphs = 0;
            do {
                final String textNumber = rs.getString("value_text");
                final String pageId = rs.getString("page_revision_id");

                LOG.trace("Found " + textNumber + " for id " + pageId);

                // Conversion
                final BigDecimal decNumber = convert(textNumber);
                if (decNumber == null) {
                    LOG.warn("Failed to convert paragraph " + pageId + " with value " + textNumber);
                }

                pstmt.setBigDecimal(1, decNumber);
                pstmt.setString(2, pageId);
                pstmt.addBatch();
                totalparagraphs++;
            } while (rs.next());

            LOG.debug("Executing updates");
            pstmt.executeBatch();
            LOG.info("Processed " + totalparagraphs + " paragraphs");
            LOG.info("Finished");
        }
    } catch (final SQLException e) {
        LOG.fatal("An error occured while converting Strings to Decimal", e);
    } finally {
        LOG.info("Releasing the resources");
        DbUtils.closeQuietly(rs);
        DbUtils.closeQuietly(pstmt);
        DbUtils.closeQuietly(stmt);
    }
}

From source file:net.solarnetwork.node.dao.jdbc.reactor.JdbcInstructionDao.java

@Override
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
public Long storeInstruction(final Instruction instruction) {
    // first store our Instruction entity
    final Long pk = storeDomainObject(instruction, getSqlResource(RESOURCE_SQL_INSERT_INSTRUCTION));

    // now store all the Instruction's parameters
    getJdbcTemplate().execute(new PreparedStatementCreator() {

        @Override/* w ww  .  j av  a2  s .c  o  m*/
        public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
            PreparedStatement ps = con.prepareStatement(getSqlResource(RESOURCE_SQL_INSERT_INSTRUCTION_PARAM));
            return ps;
        }
    }, new PreparedStatementCallback<Object>() {

        @Override
        public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
            int pos = 0;
            for (String paramName : instruction.getParameterNames()) {
                String[] paramValues = instruction.getAllParameterValues(paramName);
                if (paramValues == null || paramValues.length < 1) {
                    continue;
                }
                for (String paramValue : paramValues) {
                    int col = 1;
                    ps.setLong(col++, pk);
                    ps.setLong(col++, pos);
                    ps.setString(col++, paramName);
                    ps.setString(col++, paramValue);
                    ps.addBatch();
                    pos++;
                }
            }
            int[] batchResults = ps.executeBatch();
            if (log.isTraceEnabled()) {
                log.trace("Batch inserted {} instruction params: {}", pos, Arrays.toString(batchResults));
            }
            return null;
        }
    });

    // finally crate a status row
    Date statusDate = new Date();
    getJdbcTemplate().update(getSqlResource(RESOURCE_SQL_INSERT_INSTRUCTION_STATUS), pk,
            new java.sql.Timestamp(statusDate.getTime()), InstructionState.Received.toString());
    return pk;
}

From source file:edu.ucsb.cs.eager.dao.EagerDependencyMgtDAO.java

private void saveDependencies(Connection conn, ApplicationInfo app) throws SQLException {
    if (app.getDependencies() == null && app.getEnclosedAPIs() == null) {
        return;/*www .  j a  v  a2 s  .c o  m*/
    }
    String insertQuery = "INSERT INTO EAGER_API_DEPENDENCY (EAGER_DEPENDENCY_NAME, "
            + "EAGER_DEPENDENCY_VERSION, EAGER_DEPENDENT_NAME, EAGER_DEPENDENT_VERSION, "
            + "EAGER_DEPENDENCY_OPERATIONS) VALUES (?,?,?,?,?)";
    PreparedStatement psInsert = null;
    try {
        psInsert = conn.prepareStatement(insertQuery);
        if (app.getDependencies() != null) {
            for (DependencyInfo dependency : app.getDependencies()) {
                psInsert.setString(1, dependency.getName());
                psInsert.setString(2, dependency.getVersion());
                psInsert.setString(3, app.getName());
                psInsert.setString(4, app.getVersion());
                psInsert.setString(5, getOperationsListAsString(dependency));
                psInsert.addBatch();
            }
        }
        if (app.getEnclosedAPIs() != null) {
            for (APIInfo enclosedAPI : app.getEnclosedAPIs()) {
                psInsert.setString(1, app.getName());
                psInsert.setString(2, app.getVersion());
                psInsert.setString(3, enclosedAPI.getName());
                psInsert.setString(4, enclosedAPI.getVersion());
                psInsert.setString(5, "");
                psInsert.addBatch();
            }
        }
        psInsert.executeBatch();
        psInsert.clearBatch();
    } finally {
        APIMgtDBUtil.closeAllConnections(psInsert, null, null);
    }
}

From source file:org.wso2.carbon.certificate.mgt.core.dao.impl.AbstractCertificateDAOImpl.java

@Override
public void addCertificate(List<Certificate> certificates) throws CertificateManagementDAOException {
    Connection conn;/*from  ww w. ja  v a  2s.  c  om*/
    PreparedStatement stmt = null;
    try {
        conn = this.getConnection();
        stmt = conn.prepareStatement(
                "INSERT INTO DM_DEVICE_CERTIFICATE (SERIAL_NUMBER, CERTIFICATE, TENANT_ID, USERNAME)"
                        + " VALUES (?,?,?,?)");
        PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext
                .getThreadLocalCarbonContext();
        String username = threadLocalCarbonContext.getUsername();
        for (Certificate certificate : certificates) {
            // the serial number of the certificate used for its creation is set as its alias.
            String serialNumber = certificate.getSerial();
            if (serialNumber == null || serialNumber.isEmpty()) {
                serialNumber = String.valueOf(certificate.getCertificate().getSerialNumber());
            }
            byte[] bytes = Serializer.serialize(certificate.getCertificate());

            stmt.setString(1, serialNumber);
            stmt.setBytes(2, bytes);
            stmt.setInt(3, certificate.getTenantId());
            stmt.setString(4, username);
            stmt.addBatch();
        }
        stmt.executeBatch();
    } catch (SQLException | IOException e) {
        throw new CertificateManagementDAOException("Error occurred while saving certificates. ", e);
    } finally {
        CertificateManagementDAOUtil.cleanupResources(stmt, null);
    }
}

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

@Override
public void updateAttempts(List<Integer> deviceIds, boolean reset) throws MonitoringDAOException {
    Connection conn;/*from   w  ww .  j  a  va2s .c o  m*/
    PreparedStatement stmt = null;
    Timestamp currentTimestamp = new Timestamp(Calendar.getInstance().getTime().getTime());
    int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
    try {
        conn = this.getConnection();
        String query = "";
        if (reset) {
            query = "UPDATE DM_POLICY_COMPLIANCE_STATUS SET ATTEMPTS = 0, LAST_REQUESTED_TIME = ? "
                    + "WHERE DEVICE_ID = ? AND TENANT_ID = ?";
        } else {
            query = "UPDATE DM_POLICY_COMPLIANCE_STATUS SET ATTEMPTS = ATTEMPTS + 1, LAST_REQUESTED_TIME = ? "
                    + "WHERE DEVICE_ID = ? AND TENANT_ID = ?";
        }
        stmt = conn.prepareStatement(query);
        for (int deviceId : deviceIds) {
            stmt.setTimestamp(1, currentTimestamp);
            stmt.setInt(2, deviceId);
            stmt.setInt(3, tenantId);
            stmt.addBatch();
        }
        stmt.executeBatch();
    } catch (SQLException e) {
        throw new MonitoringDAOException("Unable to update the attempts  data in database.", e);
    } finally {
        PolicyManagementDAOUtil.cleanupResources(stmt, null);
    }
}