Example usage for java.sql Statement SUCCESS_NO_INFO

List of usage examples for java.sql Statement SUCCESS_NO_INFO

Introduction

In this page you can find the example usage for java.sql Statement SUCCESS_NO_INFO.

Prototype

int SUCCESS_NO_INFO

To view the source code for java.sql Statement SUCCESS_NO_INFO.

Click Source Link

Document

The constant indicating that a batch statement executed successfully but that no count of the number of rows it affected is available.

Usage

From source file:Main.java

public static void checkUpdateCounts(int[] updateCounts) {
    for (int i = 0; i < updateCounts.length; i++) {
        if (updateCounts[i] >= 0) {
            System.out.println("OK; updateCount=" + updateCounts[i]);
        } else if (updateCounts[i] == Statement.SUCCESS_NO_INFO) {
            System.out.println("OK; updateCount=Statement.SUCCESS_NO_INFO");
        } else if (updateCounts[i] == Statement.EXECUTE_FAILED) {
            System.out.println("Failure; updateCount=Statement.EXECUTE_FAILED");
        }// www.  j  ava 2s . c  om
    }
}

From source file:com.nabla.wapp.server.database.Database.java

public static boolean isBatchCompleted(final int[] results) {
    if (results == null)
        return false;
    for (int i = 0; i < results.length; i++) {
        final int result = results[i];
        if (result < 0 && result != Statement.SUCCESS_NO_INFO)
            return false;
    }//from ww  w.ja v  a2  s .com
    return true;
}

From source file:com.dattack.dbcopy.engine.InsertOperationContext.java

private int executeBatch() throws SQLException {

    int insertedRows = 0;
    try {/*from ww  w .  j  av  a2 s.  c om*/
        final int[] batchResult = getPreparedStatement().executeBatch();

        for (int i = 0; i < batchResult.length; i++) {
            if (batchResult[i] > 0) {
                insertedRows += batchResult[i];
            } else if (batchResult[i] == Statement.SUCCESS_NO_INFO) {
                insertedRows++;
            }
        }

    } catch (final BatchUpdateException e) {
        LOGGER.warn("Batch operation failed: {} (SQLSTATE: {}, Error code: {}, Executed statements: {})",
                e.getMessage(), e.getSQLState(), e.getErrorCode(), e.getUpdateCounts().length);
    }

    getConnection().commit();
    return insertedRows;
}

From source file:com.adaptris.core.services.jdbc.JdbcBatchingDataCaptureService.java

protected static long rowsUpdated(int[] rc) throws SQLException {
    List<Integer> result = Arrays.asList(ArrayUtils.toObject(rc));
    if (result.contains(Statement.EXECUTE_FAILED)) {
        throw new SQLException("Batch Execution Failed.");
    }/* w ww  .ja  v a 2  s . co m*/
    return result.stream().filter(e -> !(e == Statement.SUCCESS_NO_INFO)).mapToLong(i -> i).sum();
}

From source file:org.apache.ddlutils.platform.PlatformImplBase.java

/**
 * Performs the batch for the given statement, and checks that the specified amount of rows have been changed.
 * /*from w ww  . j  a va  2s  . com*/
 * @param statement The prepared statement
 * @param numRows   The number of rows that should change
 * @param table     The changed table
 */
private void executeBatch(PreparedStatement statement, int numRows, Table table)
        throws DatabaseOperationException {
    if (statement != null) {
        try {
            Connection connection = statement.getConnection();

            beforeInsert(connection, table);

            int[] results = statement.executeBatch();

            closeStatement(statement);
            afterInsert(connection, table);

            boolean hasSum = true;
            int sum = 0;

            for (int idx = 0; (results != null) && (idx < results.length); idx++) {
                if (results[idx] < 0) {
                    hasSum = false;
                    if (results[idx] == Statement.EXECUTE_FAILED) {
                        _log.warn("The batch insertion of row " + idx + " into table " + table.getName()
                                + " failed but the driver is able to continue processing");
                    } else if (results[idx] != Statement.SUCCESS_NO_INFO) {
                        _log.warn("The batch insertion of row " + idx + " into table " + table.getName()
                                + " returned an undefined status value " + results[idx]);
                    }
                } else {
                    sum += results[idx];
                }
            }
            if (hasSum && (sum != numRows)) {
                _log.warn("Attempted to insert " + numRows + " rows into table " + table.getName()
                        + " but changed " + sum + " rows");
            }
        } catch (SQLException ex) {
            if (ex instanceof BatchUpdateException) {
                SQLException sqlEx = ((BatchUpdateException) ex).getNextException();

                throw new DatabaseOperationException("Error while inserting into the database", sqlEx);
            } else {
                throw new DatabaseOperationException("Error while inserting into the database", ex);
            }
        }
    }
}

From source file:org.jumpmind.db.sql.JdbcSqlTransaction.java

/**
 * According to the executeUpdate() javadoc -2 means that the result was
 * successful, but that the number of rows affected is unknown. since we
 * know that only one row is suppose to be affected, we'll default to 1.
 * /*w  w  w.ja v a 2  s .c  om*/
 * @param value
 */
protected final int normalizeUpdateCount(int value) {
    if (value == Statement.SUCCESS_NO_INFO) {
        value = 1;
    }
    return value;
}

From source file:org.openmrs.module.formentry.databasechange.MigrateXsltsAndTemplatesChangeset.java

private void migrateResources(JdbcConnection connection, boolean isXslt) throws CustomChangeException {
    Statement selectStmt = null;/*w w  w.ja v a 2s.c o  m*/
    PreparedStatement insertResourcesStmt = null;
    PreparedStatement insertClobsStmt = null;
    Boolean originalAutoCommit = null;
    ResultSet rs = null;
    String resourceName = (isXslt) ? FormEntryConstants.FORMENTRY_XSLT_FORM_RESOURCE_NAME
            : FormEntryConstants.FORMENTRY_TEMPLATE_FORM_RESOURCE_NAME;
    String columnName = (isXslt) ? "xslt" : "template";

    try {
        originalAutoCommit = connection.getAutoCommit();
        selectStmt = connection.createStatement();
        boolean hasResults = selectStmt.execute("SELECT form_id, " + columnName + " FROM form WHERE "
                + columnName + " IS NOT NULL AND " + columnName + " != ''");
        if (hasResults) {
            rs = selectStmt.getResultSet();
            insertClobsStmt = connection
                    .prepareStatement("INSERT INTO clob_datatype_storage (value, uuid) VALUES(?,?)");
            insertResourcesStmt = connection.prepareStatement(
                    "INSERT INTO form_resource (form_id, name, value_reference, datatype, preferred_handler, uuid) VALUES (?,'"
                            + resourceName + "',?,'" + LongFreeTextDatatype.class.getName() + "','"
                            + LongFreeTextFileUploadHandler.class.getName() + "',?)");

            String defaultXslt = IOUtils
                    .toString(getClass().getClassLoader().getResourceAsStream("default.xslt"));
            //intentionally didn't check for NULL so the exception halts the changeset
            defaultXslt = defaultXslt.trim();

            while (rs.next()) {
                String resourceValue = rs.getString(columnName);
                //if the form has an xslt and it differs from the default one
                if (StringUtils.isNotBlank(resourceValue)
                        && (!isXslt || !resourceValue.trim().equals(defaultXslt))) {
                    //set the clob storage values
                    String clobUuid = UUID.randomUUID().toString();
                    insertClobsStmt.setString(1, resourceValue.trim());
                    insertClobsStmt.setString(2, clobUuid);
                    insertClobsStmt.addBatch();

                    //set the resource column values
                    insertResourcesStmt.setInt(1, rs.getInt("form_id"));
                    insertResourcesStmt.setString(2, clobUuid);
                    insertResourcesStmt.setString(3, UUID.randomUUID().toString());
                    insertResourcesStmt.addBatch();
                }
            }

            boolean successfullyAddedClobs = false;
            int[] clobInsertCounts = insertClobsStmt.executeBatch();
            if (clobInsertCounts != null) {
                for (int i = 0; i < clobInsertCounts.length; i++) {
                    if (clobInsertCounts[i] > -1) {
                        successfullyAddedClobs = true;
                        log.debug("Successfully inserted resource clobs: insert count=" + clobInsertCounts[i]);
                    } else if (clobInsertCounts[i] == Statement.SUCCESS_NO_INFO) {
                        successfullyAddedClobs = true;
                        log.debug("Successfully inserted resource clobs; No Success info");
                    } else if (clobInsertCounts[i] == Statement.EXECUTE_FAILED) {
                        log.warn("Failed to insert resource clobs");
                    }
                }
            }

            if (successfullyAddedClobs) {
                int[] resourceInsertCounts = insertResourcesStmt.executeBatch();
                if (resourceInsertCounts != null) {
                    boolean commit = false;
                    for (int i = 0; i < resourceInsertCounts.length; i++) {
                        if (resourceInsertCounts[i] > -1) {
                            commit = true;
                            log.debug("Successfully inserted " + columnName + " resources: insert count="
                                    + resourceInsertCounts[i]);
                        } else if (resourceInsertCounts[i] == Statement.SUCCESS_NO_INFO) {
                            commit = true;
                            log.debug("Successfully inserted " + columnName + " resources; No Success info");
                        } else if (resourceInsertCounts[i] == Statement.EXECUTE_FAILED) {
                            log.warn("Failed to insert " + columnName + " resources");
                        }
                    }

                    if (commit) {
                        log.debug("Committing " + columnName + " resource inserts...");
                        connection.commit();
                    }
                }
            }
        }
    } catch (Exception e) {
        log.warn("Error generated while processsing generation of " + columnName + " form resources", e);

        try {
            if (connection != null) {
                connection.rollback();
            }
        } catch (Exception ex) {
            log.error("Failed to rollback", ex);
        }

        throw new CustomChangeException(e);
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                log.warn("Failed to close the resultset object");
            }
        }
        if (connection != null && originalAutoCommit != null) {
            try {
                connection.setAutoCommit(originalAutoCommit);
            } catch (DatabaseException e) {
                log.error("Failed to reset auto commit", e);
            }
        }

        closeStatementQuietly(selectStmt);
        closeStatementQuietly(insertClobsStmt);
        closeStatementQuietly(insertResourcesStmt);
    }
}

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

/**
 * Executes all the changes to the concept names as a batch update.
 *
 * @param connection The database connection
 *///from   w w w. j a va 2s.  co m
private void runBatchInsert(JdbcConnection connection) throws CustomChangeException {
    PreparedStatement pStmt = null;
    ResultSet rs = null;
    try {
        connection.setAutoCommit(false);

        Integer userId = DatabaseUpdater.getAuthenticatedUserId();
        //if we have no authenticated user(for API users), set as Daemon
        if (userId == null || userId < 1) {
            userId = getInt(connection, "SELECT min(user_id) FROM users");
            //leave it as null rather than setting it to 0
            if (userId < 1) {
                userId = null;
            }
        }

        //userId is not a param, because it's easier this way if it's null
        pStmt = connection.prepareStatement("INSERT INTO concept_map_type "
                + "(concept_map_type_id, name, is_hidden, retired, creator, date_created, uuid) VALUES(?,?,?,?,"
                + userId + ",?,?)");

        int mapTypeId = 1;

        for (String map : visibleConceptMapTypeArray) {
            String[] mapTypeAndUuid = map.trim().split("\\|");
            String mapType = mapTypeAndUuid[0];
            String mapUuid = mapTypeAndUuid[1];

            pStmt.setInt(1, mapTypeId);
            pStmt.setString(2, mapType);
            pStmt.setBoolean(3, false);
            pStmt.setBoolean(4, false);
            pStmt.setDate(5, new Date(Calendar.getInstance().getTimeInMillis()));
            pStmt.setString(6, mapUuid);
            pStmt.addBatch();

            mapTypeId++;
        }

        for (String map : hiddenConceptMapTypeArray) {
            String[] mapTypeAndUuid = map.trim().split("\\|");
            String mapType = mapTypeAndUuid[0];
            String mapUuid = mapTypeAndUuid[1];

            pStmt.setInt(1, mapTypeId);
            pStmt.setString(2, mapType);
            pStmt.setBoolean(3, true);
            pStmt.setBoolean(4, false);
            pStmt.setDate(5, new Date(Calendar.getInstance().getTimeInMillis()));
            pStmt.setString(6, mapUuid);
            pStmt.addBatch();

            mapTypeId++;
        }

        try {
            int[] updateCounts = pStmt.executeBatch();
            for (int i = 0; i < updateCounts.length; i++) {
                if (updateCounts[i] > -1) {
                    log.debug("Successfully executed: updateCount=" + updateCounts[i]);
                } else if (updateCounts[i] == Statement.SUCCESS_NO_INFO) {
                    log.debug("Successfully executed; No Success info");
                } else if (updateCounts[i] == Statement.EXECUTE_FAILED) {
                    log.warn("Failed to execute insert");
                }
            }

            log.debug("Committing inserts...");
            connection.commit();
        } catch (BatchUpdateException be) {
            log.warn("Error generated while processsing batch insert", be);
            int[] updateCounts = be.getUpdateCounts();

            for (int i = 0; i < updateCounts.length; i++) {
                if (updateCounts[i] > -1) {
                    log.warn("Executed with exception: insertCount=" + updateCounts[i]);
                } else if (updateCounts[i] == Statement.SUCCESS_NO_INFO) {
                    log.warn("Executed with exception; No Success info");
                } else if (updateCounts[i] == Statement.EXECUTE_FAILED) {
                    log.warn("Failed to execute insert with exception");
                }
            }

            try {
                log.debug("Rolling back batch", be);
                connection.rollback();
            } catch (Exception rbe) {
                log.warn("Error generated while rolling back batch insert", be);
            }

            //marks the changeset as a failed one
            throw new CustomChangeException("Failed to insert one or more concept map types", be);
        }
    } catch (DatabaseException e) {
        throw new CustomChangeException("Failed to insert one or more concept map types:", e);
    } catch (SQLException e) {
        throw new CustomChangeException("Failed to insert one or more concept map types:", e);
    } finally {
        //reset to auto commit mode
        try {
            connection.setAutoCommit(true);
        } catch (DatabaseException e) {
            log.warn("Failed to reset auto commit back to true", e);
        }
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                log.warn("Failed to close the resultset object");
            }
        }

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

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

/**
 * Convenience method that inserts rows into the concept reference term table. The
 * concept_map_id values becomes the concept_reference_term_id values
 * //from   w ww.  ja  v  a2  s  .  c o m
 * @param connection the current database connection
 * @param listOfPropertyValueMaps a list of property and value maps for the objects to insert
 * @throws CustomChangeException
 */
private void insertRows(JdbcConnection connection, List<Map<String, Object>> listOfPropertyValueMaps)
        throws CustomChangeException {
    if (CollectionUtils.isNotEmpty(listOfPropertyValueMaps)) {
        PreparedStatement pStmt = null;
        try {
            connection.setAutoCommit(false);
            pStmt = connection.prepareStatement("INSERT INTO concept_reference_term"
                    + "(concept_reference_term_id, concept_source_id, code, description, creator, date_created, retired, uuid) "
                    + "VALUES(?, ?, ?, ?, ?, ?, ?, ?)");

            for (Map<String, Object> propertyValueMap : listOfPropertyValueMaps) {
                pStmt.setInt(1, (Integer) propertyValueMap.get("termId"));
                pStmt.setInt(2, (Integer) propertyValueMap.get("sourceId"));
                pStmt.setString(3, propertyValueMap.get("code").toString());
                pStmt.setString(4, (propertyValueMap.get("description") == null) ? null
                        : propertyValueMap.get("description").toString());
                pStmt.setInt(5, (Integer) propertyValueMap.get("creator"));
                pStmt.setDate(6, (Date) propertyValueMap.get("dateCreated"));
                pStmt.setBoolean(7, false);
                pStmt.setString(8, propertyValueMap.get("uuid").toString());

                pStmt.addBatch();
            }

            try {
                int[] updateCounts = pStmt.executeBatch();
                for (int i = 0; i < updateCounts.length; i++) {
                    if (updateCounts[i] > -1) {
                        log.debug("Successfully executed: updateCount=" + updateCounts[i]);
                    } else if (updateCounts[i] == Statement.SUCCESS_NO_INFO) {
                        log.debug("Successfully executed; No Success info");
                    } else if (updateCounts[i] == Statement.EXECUTE_FAILED) {
                        log.warn("Failed to execute update");
                    }
                }

                log.debug("Committing updates...");
                connection.commit();
            } catch (BatchUpdateException be) {
                log.warn("Error generated while processsing batch update", be);
                int[] updateCounts = be.getUpdateCounts();

                for (int i = 0; i < updateCounts.length; i++) {
                    if (updateCounts[i] > -1) {
                        log.warn("Executed with exception: updateCount=" + updateCounts[i]);
                    } else if (updateCounts[i] == Statement.SUCCESS_NO_INFO) {
                        log.warn("Executed with exception; No Success info");
                    } else if (updateCounts[i] == Statement.EXECUTE_FAILED) {
                        log.warn("Failed to execute update with exception");
                    }
                }

                try {
                    log.warn("Rolling back batch", be);
                    connection.rollback();
                } catch (Exception rbe) {
                    log.warn("Error generated while rolling back batch update", be);
                }

                //marks the changeset as a failed one
                throw new CustomChangeException(
                        "Failed to generate concept reference terms from existing concept mappings.");
            }
        } catch (DatabaseException e) {
            throw new CustomChangeException("Error generated", e);
        } catch (SQLException e) {
            throw new CustomChangeException("Error generated", e);
        } finally {
            //reset to auto commit mode
            try {
                connection.setAutoCommit(true);
            } catch (DatabaseException e) {
                log.warn("Failed to reset auto commit back to true", e);
            }

            if (pStmt != null) {
                try {
                    pStmt.close();
                } catch (SQLException e) {
                    log.warn("Failed to close the prepared statement object");
                }
            }
        }
    } else
        log.error("List of property value maps is null or empty");
}

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

/**
 * Executes all the changes to the concept names as a batch update.
 *
 * @param connection The database connection
 *//*from   w  w w.  j a  v a2 s.com*/
private void runBatchUpdate(JdbcConnection connection) {
    PreparedStatement pStmt = null;

    try {
        connection.setAutoCommit(false);
        pStmt = connection.prepareStatement(
                "UPDATE concept_name SET locale = ?, concept_name_type = ?, locale_preferred = ?, voided = ?, date_voided = ?, void_reason = ?, voided_by = ? WHERE concept_name_id = ?");

        Integer userId = DatabaseUpdater.getAuthenticatedUserId();
        //is we have no authenticated user(for API users), set as Daemon
        if (userId == null || userId < 1) {
            userId = getInt(connection, "SELECT min(user_id) FROM users");
            //leave it as null rather than setting it to 0
            if (userId < 1) {
                userId = null;
            }
        }

        for (ConceptName conceptName : updatedConceptNames) {
            pStmt.setString(1, conceptName.getLocale().toString());
            pStmt.setString(2,
                    (conceptName.getConceptNameType() != null) ? conceptName.getConceptNameType().toString()
                            : null);
            pStmt.setBoolean(3, conceptName.isLocalePreferred());
            pStmt.setBoolean(4, conceptName.isVoided());
            pStmt.setDate(5, conceptName.isVoided() ? new Date(System.currentTimeMillis()) : null);
            pStmt.setString(6, conceptName.getVoidReason());
            // "Not all databases allow for a non-typed Null to be sent to the backend", so we can't use setInt
            pStmt.setObject(7, (conceptName.isVoided() && userId != null) ? userId : null, Types.INTEGER);
            pStmt.setInt(8, conceptName.getConceptNameId());

            pStmt.addBatch();
        }

        try {
            int[] updateCounts = pStmt.executeBatch();
            for (int i = 0; i < updateCounts.length; i++) {
                if (updateCounts[i] > -1) {
                    log.debug("Successfully executed: updateCount=" + updateCounts[i]);
                } else if (updateCounts[i] == Statement.SUCCESS_NO_INFO) {
                    log.debug("Successfully executed; No Success info");
                } else if (updateCounts[i] == Statement.EXECUTE_FAILED) {
                    log.warn("Failed to execute update");
                }
            }

            log.debug("Committing updates...");
            connection.commit();
        } catch (BatchUpdateException be) {
            log.warn("Error generated while processsing batch update", be);
            int[] updateCounts = be.getUpdateCounts();

            for (int i = 0; i < updateCounts.length; i++) {
                if (updateCounts[i] > -1) {
                    log.warn("Executed with exception: updateCount=" + updateCounts[i]);
                } else if (updateCounts[i] == Statement.SUCCESS_NO_INFO) {
                    log.warn("Executed with exception; No Success info");
                } else if (updateCounts[i] == Statement.EXECUTE_FAILED) {
                    log.warn("Failed to execute update with exception");
                }
            }

            try {
                log.warn("Rolling back batch", be);
                connection.rollback();
            } catch (Exception rbe) {
                log.warn("Error generated while rolling back batch update", be);
            }
        }
    } catch (SQLException e) {
        log.warn("Error generated", e);
    } catch (DatabaseException e) {
        log.warn("Error generated", e);
    } finally {
        //reset to auto commit mode
        try {
            connection.setAutoCommit(true);
        } catch (DatabaseException e) {
            log.warn("Failed to reset auto commit back to true", e);
        }

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