Example usage for java.sql PreparedStatement getUpdateCount

List of usage examples for java.sql PreparedStatement getUpdateCount

Introduction

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

Prototype

int getUpdateCount() throws SQLException;

Source Link

Document

Retrieves the current result as an update count; if the result is a ResultSet object or there are no more results, -1 is returned.

Usage

From source file:com.draagon.meta.manager.db.driver.GenericSQLDriver.java

@Override
public boolean create(Connection c, MetaObject mc, ObjectMappingDB omdb, Object o) throws SQLException {

    // Check if there is table inheritence going on, and if so create the super table first
    BaseDef base = omdb.getDBDef();/*from w  ww. ja v  a  2  s. com*/
    if (base instanceof TableDef) {
        TableDef table = (TableDef) base;

        InheritenceDef inheritence = table.getInheritence();
        if (inheritence != null) {
            ObjectMappingDB smom = (ObjectMappingDB) omdb.getSuperMapping();

            // Set the discriminator values
            if (inheritence.getDiscriminatorName() != null) {
                MetaField df = omdb.getField(inheritence.getDiscriminatorName());
                df.setString(o, inheritence.getDiscriminatorValue());
            }

            // Create the super classes table entry
            if (!create(c, mc, smom, o)) {
                throw new SQLException("Super table entry could not be created for mapping [" + smom + "]");
            }

            // Set the mapping field
            MetaField rf = omdb.getField(inheritence.getRefColumn());
            MetaField f = omdb.getField(inheritence.getColumnName());
            f.setObject(o, rf.getObject(o));
        }
    }

    // Now create the entry for this object
    PreparedStatement s = getInsertStatement(c, mc, omdb, o);

    try {
        s.execute();

        if (s.getUpdateCount() < 1) {
            return false;
        } else {

            setLastIds(c, mc, omdb, o);

            return true;
        }
    } finally {
        s.close();
    }
}

From source file:org.wso2.carbon.appfactory.core.dao.JDBCApplicationDAO.java

/**
 * Helper method to add a empty holder for build status
 *
 * @param repositoryID       repo id//from   www  .  ja  v  a 2 s  .com
 * @param databaseConnection existing connection
 * @return true if it success ,false if it failed
 * @throws AppFactoryException
 */
private boolean addBuildStatus(int repositoryID, Connection databaseConnection) throws AppFactoryException {
    PreparedStatement preparedStatement = null;
    try {
        preparedStatement = databaseConnection.prepareStatement(SQLConstants.ADD_BUILD_STATUS_SQL);
        preparedStatement.setInt(1, repositoryID);
        preparedStatement.setInt(2, CarbonContext.getThreadLocalCarbonContext().getTenantId());
        preparedStatement.execute();
        int affectedRow = preparedStatement.getUpdateCount();
        if (affectedRow > 0) {
            return true;
        }
        handleException("Error while inserting build status for repository : " + repositoryID);
    } catch (SQLException e) {
        handleException("Error while inserting build status for repository : " + repositoryID, e);
    } finally {
        AppFactoryDBUtil.closePreparedStatement(preparedStatement);
    }

    return false;
}

From source file:org.wso2.carbon.appfactory.core.dao.JDBCApplicationDAO.java

/**
 * Helper method to add a empty holder for deploy status
 *
 * @param repositoryID       repository ID
 * @param environment        stage/*  ww w  .  j ava 2s.  co  m*/
 * @param databaseConnection existing db connection
 * @return true if it success ,false if it failed
 * @throws AppFactoryException
 */
private boolean addDeployStatus(int repositoryID, String environment, Connection databaseConnection)
        throws AppFactoryException {
    PreparedStatement preparedStatement = null;
    try {
        preparedStatement = databaseConnection.prepareStatement(SQLConstants.ADD_DEPLOY_STATUS_SQL);
        preparedStatement.setInt(1, repositoryID);
        preparedStatement.setString(2, environment);
        preparedStatement.setInt(3, CarbonContext.getThreadLocalCarbonContext().getTenantId());
        preparedStatement.execute();
        int affectedRow = preparedStatement.getUpdateCount();
        if (affectedRow > 0) {
            return true;
        }
        handleException("Error while inserting deploy status for repository : " + repositoryID);
    } catch (SQLException e) {
        handleException("Error while inserting deploy status for repository : " + repositoryID, e);
    } finally {
        AppFactoryDBUtil.closePreparedStatement(preparedStatement);
    }

    return false;
}

From source file:com.toxind.benchmark.thrid.ibatis.sqlmap.engine.execution.SqlExecutor.java

/**
 * Execute an update// w  ww .ja v  a2s.c o m
 * 
 * @param statementScope
 *            - the request scope
 * @param conn
 *            - the database connection
 * @param sql
 *            - the sql statement to execute
 * @param parameters
 *            - the parameters for the sql statement
 * @return - the number of records changed
 * @throws SQLException
 *             - if the update fails
 */
public int executeUpdate(StatementScope statementScope, Connection conn, String sql, Object[] parameters)
        throws SQLException {
    ErrorContext errorContext = statementScope.getErrorContext();
    errorContext.setActivity("executing update");
    errorContext.setObjectId(sql);
    PreparedStatement ps = null;
    setupResultObjectFactory(statementScope);
    int rows = 0;
    try {
        errorContext.setMoreInfo("Check the SQL Statement (preparation failed).");
        ps = prepareStatement(statementScope.getSession(), conn, sql);
        setStatementTimeout(statementScope.getStatement(), ps);
        errorContext.setMoreInfo("Check the parameters (set parameters failed).");
        statementScope.getParameterMap().setParameters(statementScope, ps, parameters);
        errorContext.setMoreInfo("Check the statement (update failed).");

        // ========================== print
        try {
            if (log.isInfoEnabled()) {
                int count = ps.getParameterMetaData().getParameterCount();
                for (int i = 0; i < count; i++) {
                    sql = sql.replaceFirst("\\?",
                            parameters[i].getClass().getName().equals("java.lang.String")
                                    ? "'" + parameters[i].toString() + "'"
                                    : parameters[i].toString());
                }
                String[] unPrintSql = { "update dw_websql_sqlcommand a set a.status = 1" };
                printSql(sql, unPrintSql);
            }
        } catch (Throwable t) {

        }
        // =========================== print

        ps.execute();
        rows = ps.getUpdateCount();
    } finally {
        closeStatement(statementScope.getSession(), ps);
    }
    return rows;
}

From source file:org.wso2.carbon.appfactory.core.dao.JDBCApplicationDAO.java

private boolean addRepository(int versionID, boolean isForked, String username, Connection databaseConnection)
        throws AppFactoryException {
    PreparedStatement preparedStatement = null;
    try {//  w  w w. j  a  v a  2  s .  c o  m
        preparedStatement = databaseConnection.prepareStatement(SQLConstants.ADD_APPLICATION_REPOSITORY_SQL);
        preparedStatement.setInt(1, versionID);
        preparedStatement.setInt(2, isForked ? 1 : 0);
        preparedStatement.setString(3, username);
        preparedStatement.setInt(4, CarbonContext.getThreadLocalCarbonContext().getTenantId());
        preparedStatement.execute();
        int affectedRows = preparedStatement.getUpdateCount();
        if (affectedRows > 0) {
            int repositoryID = getAutoIncrementRepositoryID(versionID, isForked, username, databaseConnection);
            addBuildStatus(repositoryID, databaseConnection);
            String stages[] = ServiceHolder.getAppFactoryConfiguration()
                    .getProperties(AppFactoryConstants.DEPLOYMENT_STAGES);
            for (String stage : stages) {
                addDeployStatus(repositoryID, stage, databaseConnection);
            }
            return true;
        }
        handleException("Adding repository failed for version : " + versionID);
    } catch (SQLException e) {
        handleException("Adding repository failed for version : " + versionID, e);
    } finally {
        AppFactoryDBUtil.closePreparedStatement(preparedStatement);
    }
    return false;
}

From source file:org.wso2.carbon.appfactory.core.dao.JDBCApplicationDAO.java

/**
 * It will add application with default initial version 'trunk'
 *
 * @param application Application with given key
 * @return true if it successful false if it failed
 * @throws AppFactoryException if there is a problem in creating application
 *//*  w  w  w . jav a  2s.c  om*/
public boolean addApplication(Application application) throws AppFactoryException {
    Connection databaseConnection = null;
    PreparedStatement preparedStatement = null;
    int tenantID = CarbonContext.getThreadLocalCarbonContext().getTenantId();
    try {
        databaseConnection = AppFactoryDBUtil.getConnection();
        preparedStatement = databaseConnection.prepareStatement(SQLConstants.ADD_APPLICATION_SQL);
        preparedStatement.setString(1, application.getId());
        preparedStatement.setString(2, application.getName());
        preparedStatement.setInt(3, tenantID);
        preparedStatement.execute();
        int updatedRowCount = preparedStatement.getUpdateCount();
        if (updatedRowCount > 0) {

            //debug log
            handleDebugLog((new StringBuilder()).append("successfully added application.Updated ")
                    .append(updatedRowCount).append(" rows").toString());
            Version version = AppFactoryCoreUtil.isUplodableAppType(application.getType())
                    ? new Version(SQLParameterConstants.VERSION_1_0_0,
                            AppFactoryConstants.ApplicationStage.PRODUCTION.getCapitalizedString())
                    : new Version(SQLParameterConstants.VERSION_TRUNK,
                            AppFactoryConstants.ApplicationStage.DEVELOPMENT.getCapitalizedString());
            addVersion(version, databaseConnection, application.getId());
            databaseConnection.commit();
            return true;
        }

        String errorMessage = "Adding application is failed for " + application.getId();
        handleException(errorMessage); // This is not caught within this method.
    } catch (SQLException e) {
        try {
            if (databaseConnection != null) {
                databaseConnection.rollback();
            }
        } catch (SQLException e1) {
            // Only logging this exception since this is not the main issue. The original issue is thrown.
            log.error("Error while rolling back the added application", e1);
        }

        String errorMsg = "Error while adding the application " + application.getId();
        handleException(errorMsg, e);
    } finally {
        AppFactoryDBUtil.closePreparedStatement(preparedStatement);
        AppFactoryDBUtil.closeConnection(databaseConnection);
    }
    return false;
}

From source file:org.wso2.carbon.appfactory.core.dao.JDBCApplicationDAO.java

/**
 * Add failed application to the AF_FAILED_APPLICATION table
 *
 * @param applicationKey application key
 * @return true if it successful/*from  w w  w .  ja v  a 2s.  c  o  m*/
 * @throws AppFactoryException
 */
public boolean addFailedApplication(String applicationKey) throws AppFactoryException {
    Connection databaseConnection = null;
    PreparedStatement preparedStatement = null;
    int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
    try {
        databaseConnection = AppFactoryDBUtil.getConnection();
        preparedStatement = databaseConnection.prepareStatement(SQLConstants.ADD_FAILED_APPLICATION_SQL);
        preparedStatement.setString(1, applicationKey);
        preparedStatement.setInt(2, tenantId);
        preparedStatement.setTimestamp(3, new Timestamp(System.currentTimeMillis()));
        preparedStatement.execute();
        int updatedRowCount = preparedStatement.getUpdateCount();
        if (updatedRowCount > 0) {
            //debug log
            handleDebugLog((new StringBuilder()).append("successfully added failed_application. Updated ")
                    .append(updatedRowCount).append(" rows").toString());
            databaseConnection.commit();
            return true;
        }

        String errorMessage = "Adding failed_application is failed for " + applicationKey;
        handleException(errorMessage); // This is not caught within this method.
    } catch (SQLException e) {
        try {
            if (databaseConnection != null) {
                databaseConnection.rollback();
            }
        } catch (SQLException e1) {
            // Only logging this exception since this is not the main issue. The original issue is thrown.
            log.error("Error while rolling back the added failed_application", e1);
        }

        String errorMsg = "Error while adding the failed_application " + applicationKey;
        handleException(errorMsg, e);
    } finally {
        AppFactoryDBUtil.closePreparedStatement(preparedStatement);
        AppFactoryDBUtil.closeConnection(databaseConnection);
    }
    return false;
}

From source file:org.wso2.carbon.appfactory.core.dao.JDBCApplicationDAO.java

/**
 * Update CartridgeCluster//w  w  w.  j a  v a 2s.c  om
 *
 * @param cartridgeCluster {@link org.wso2.carbon.appfactory.core.dto.CartridgeCluster}
 * @return true if it successful, false if it is failed
 * @throws AppFactoryException if there is a problem in creating CartridgeCluster
 */
public boolean updateCartridgeCluster(CartridgeCluster cartridgeCluster) throws AppFactoryException {
    boolean result = false;
    if (cartridgeCluster != null) {
        Connection databaseConnection = null;
        PreparedStatement preparedStatement = null;
        try {
            databaseConnection = AppFactoryDBUtil.getConnection();
            preparedStatement = databaseConnection.prepareStatement(SQLConstants.UPDATE_CARTRIDGE_CLUSTER_SQL);
            preparedStatement.setString(1, cartridgeCluster.getLbClusterId());
            preparedStatement.setString(2, cartridgeCluster.getActiveIP());
            preparedStatement.setString(3, cartridgeCluster.getClusterId());
            preparedStatement.execute();
            databaseConnection.commit();
            int updatedRowCount = preparedStatement.getUpdateCount();
            if (updatedRowCount > 0) {
                result = true;
            }
        } catch (SQLException e) {
            try {
                if (databaseConnection != null) {
                    databaseConnection.rollback();
                }
            } catch (SQLException e1) {

                // no need to throw since, this is not related to business logic
                String msg = "Error while rolling back the added cartridge";
                log.error(msg, e1);
            }
            handleException("Adding cartridge is failed for clusterId : " + cartridgeCluster.getClusterId(), e);
        } finally {
            AppFactoryDBUtil.closePreparedStatement(preparedStatement);
            AppFactoryDBUtil.closeConnection(databaseConnection);
        }
    }
    return result;
}

From source file:org.wso2.carbon.appfactory.core.dao.JDBCApplicationDAO.java

/**
 * Set application creation status of an application
 *
 * @param applicationKey            application key of an application
 * @param applicationCreationStatus {@link org.wso2.carbon.appfactory.core.util.Constants.ApplicationCreationStatus}
 * @return true if it successful false if it failed
 * @throws AppFactoryException/*from   w w  w . j a v  a2  s  .c o m*/
 */
public boolean setApplicationCreationStatus(String applicationKey,
        Constants.ApplicationCreationStatus applicationCreationStatus) throws AppFactoryException {
    Connection databaseConnection = null;
    PreparedStatement preparedStatement = null;
    int tenantID = CarbonContext.getThreadLocalCarbonContext().getTenantId();
    try {
        databaseConnection = AppFactoryDBUtil.getConnection();
        preparedStatement = databaseConnection
                .prepareStatement(SQLConstants.UPDATE_APPLICATION_CREATION_STATUS_SQL);
        preparedStatement.setString(1, applicationCreationStatus.name());
        preparedStatement.setString(2, applicationKey);
        preparedStatement.setInt(3, tenantID);
        preparedStatement.execute();
        int affectedRows = preparedStatement.getUpdateCount();
        if (affectedRows > 0) {
            databaseConnection.commit();

            // We remove from cache here
            String appCreationStatusCacheKey = JDBCApplicationCacheManager
                    .constructApplicationCreationCacheKey(tenantID, applicationKey);
            Cache<String, Constants.ApplicationCreationStatus> applicationCreationStatusCache = JDBCApplicationCacheManager
                    .getApplicationCreationStatusCache();
            handleDebugLog("Removing data from the application creation status cache for application key : "
                    + applicationKey);
            applicationCreationStatusCache.remove(appCreationStatusCacheKey);
            return true;
        }
        handleException(
                "Setting application creation status is failed for application key : " + applicationKey);
    } catch (SQLException e) {
        try {
            if (databaseConnection != null) {
                databaseConnection.rollback();
            }
        } catch (SQLException e1) {

            // Only logging this exception since this is not the main issue. The original issue is thrown.
            log.error("Error while rolling back Setting application creation status for application key : "
                    + applicationKey, e1);
        }
        handleException("Setting application creation status is failed for application key : " + applicationKey,
                e);
    } finally {
        AppFactoryDBUtil.closePreparedStatement(preparedStatement);
        AppFactoryDBUtil.closeConnection(databaseConnection);
    }
    return false;
}

From source file:org.wso2.carbon.appfactory.core.dao.JDBCApplicationDAO.java

/**
 * Update the last deployed id.This will be the build number of the artifact that is
 * submitted for deployment//from  w  w  w  .  j a  v a2 s  .  c o m
 *
 * @param applicationKey key of an application
 * @param version        version name
 * @param isForked       true if it a forked version
 * @param username       the user who is forked
 * @param buildID        build number
 * @return true or false
 * @throws AppFactoryException
 */
public boolean updateLastDeployedBuildID(String applicationKey, String version, String environment,
        boolean isForked, String username, String buildID) throws AppFactoryException {
    Connection databaseConnection = null;
    PreparedStatement preparedStatement = null;
    try {
        databaseConnection = AppFactoryDBUtil.getConnection();
        preparedStatement = databaseConnection
                .prepareStatement(SQLConstants.UPDATE_DEPLOYED_BUILD_ID_IN_DEPLOY_STATUS_SQL);
        int repositoryID = getRepositoryID(applicationKey, isForked, username, version, databaseConnection);
        preparedStatement.setString(1, buildID);
        preparedStatement.setInt(2, repositoryID);
        preparedStatement.setString(3, environment);
        preparedStatement.execute();
        int affectedRows = preparedStatement.getUpdateCount();
        if (affectedRows > 0) {
            databaseConnection.commit();

            // We remove the cache entry here before the return.
            int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
            String deployCacheKey = JDBCApplicationCacheManager.constructDeployStatusCacheKey(applicationKey,
                    tenantId, version, environment, isForked, username).toLowerCase();
            Cache<String, DeployStatus> deployCache = JDBCApplicationCacheManager
                    .getApplicationDeployStatusCache();
            handleDebugLog(
                    "Removing data from the deployment status cache for application key : " + applicationKey);
            deployCache.remove(deployCacheKey);
            JDBCApplicationCacheManager.getAppVersionListCache().remove(applicationKey);
            return true;
        }
        handleException("Error while updating deployed build id for version : " + version
                + " application key : " + applicationKey);
    } catch (SQLException e) {
        try {
            if (databaseConnection != null) {
                databaseConnection.rollback();
            }
        } catch (SQLException e1) {

            // Only logging this exception since this is not the main issue. The original issue is thrown.
            log.error("Error while rolling back update deployed build id for version : " + version + " of "
                    + "application key : " + applicationKey, e1);
        }
        handleException("Error while updating deployed build id for version : " + version + " of application "
                + "key : " + applicationKey, e);
    } finally {
        AppFactoryDBUtil.closePreparedStatement(preparedStatement);
        AppFactoryDBUtil.closeConnection(databaseConnection);
    }
    return false;
}