Example usage for java.sql PreparedStatement getGeneratedKeys

List of usage examples for java.sql PreparedStatement getGeneratedKeys

Introduction

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

Prototype

ResultSet getGeneratedKeys() throws SQLException;

Source Link

Document

Retrieves any auto-generated keys created as a result of executing this Statement object.

Usage

From source file:org.wso2.appcloud.core.dao.ApplicationDAO.java

/**
 * Method for adding version details to database.
 *
 * @param dbConnection  database connection
 * @param version       version object//from   ww  w.j a v a 2 s .  c o  m
 * @param applicationId application id
 * @param tenantId      tenant id
 * @throws AppCloudException
 */
public void addVersion(Connection dbConnection, Version version, int applicationId, int tenantId)
        throws AppCloudException {

    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;

    try {

        preparedStatement = dbConnection.prepareStatement(SQLQueryConstants.ADD_VERSION,
                Statement.RETURN_GENERATED_KEYS);
        preparedStatement.setString(1, version.getVersionName());
        preparedStatement.setString(2, version.getHashId());
        preparedStatement.setInt(3, applicationId);
        preparedStatement.setInt(4, version.getRuntimeId());
        preparedStatement.setInt(5, tenantId);
        preparedStatement.setString(6, version.getConSpecCpu());
        preparedStatement.setString(7, version.getConSpecMemory());
        preparedStatement.setString(8, version.getExposureLevel());

        preparedStatement.execute();

        resultSet = preparedStatement.getGeneratedKeys();

        List<Tag> tags = version.getTags();
        if (tags != null) {
            addTags(dbConnection, tags, version.getHashId(), tenantId);
        }

        List<RuntimeProperty> runtimeProperties = version.getRuntimeProperties();
        if (runtimeProperties != null) {
            addRunTimeProperties(dbConnection, runtimeProperties, version.getHashId(), tenantId);
        }

    } catch (SQLException e) {
        String msg = "Error occurred while adding application version to database for application id : "
                + applicationId + " version : " + version.getVersionName() + " in tenant : " + tenantId;
        throw new AppCloudException(msg, e);
    } finally {
        DBUtil.closeResultSet(resultSet);
        DBUtil.closePreparedStatement(preparedStatement);
    }

}

From source file:org.wso2.appcloud.core.dao.ApplicationDAO.java

/**
 * Method for adding application details to database.
 *
 * @param dbConnection database connection
 * @param application  application object
 * @param tenantId     tenant id//w  w  w.  j a  v  a  2  s  .  c  o  m
 * @throws AppCloudException
 */
public void addApplication(Connection dbConnection, Application application, int tenantId)
        throws AppCloudException {

    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;

    try {
        int applicationId = 0;
        preparedStatement = dbConnection.prepareStatement(SQLQueryConstants.ADD_APPLICATION,
                Statement.RETURN_GENERATED_KEYS);
        preparedStatement.setString(1, application.getApplicationName());
        preparedStatement.setString(2, application.getHashId());
        preparedStatement.setString(3, application.getDescription());
        preparedStatement.setInt(4, tenantId);
        preparedStatement.setString(5, application.getDefaultVersion());
        preparedStatement.setString(6, application.getApplicationType());
        preparedStatement.setString(7, application.getCloudType());

        preparedStatement.execute();

        resultSet = preparedStatement.getGeneratedKeys();
        while (resultSet.next()) {
            applicationId = resultSet.getInt(1);
        }

        List<Version> versions = application.getVersions();

        if (versions != null) {
            for (Version version : versions) {
                addVersion(dbConnection, version, applicationId, tenantId);
            }
        }

        InputStream iconInputStream;
        if (application.getIcon() != null) {
            iconInputStream = IOUtils.toBufferedInputStream(application.getIcon().getBinaryStream());
            if (iconInputStream.available() != 0) {
                updateApplicationIcon(dbConnection, iconInputStream, applicationId, tenantId);
            }
        }

    } catch (SQLException e) {

        String msg = "Error occurred while adding application : " + application.getApplicationName()
                + " to database " + "in tenant : " + tenantId + " and cloud : " + application.getCloudType();
        throw new AppCloudException(msg, e);

    } catch (IOException e) {
        String msg = "Error while generating stream of the icon for application : "
                + application.getApplicationName() + " in tenant : " + tenantId + " and cloud : "
                + application.getCloudType();
        throw new AppCloudException(msg, e);
    } finally {
        DBUtil.closeResultSet(resultSet);
        DBUtil.closePreparedStatement(preparedStatement);
    }

}

From source file:org.apache.sqoop.repository.derby.DerbyRepositoryHandler.java

/**
 * Resolves counter id.//from  w ww. j  a  v a2  s  . co  m
 *
 * @param counter Given counter
 * @param conn Connection to database
 * @return Id
 * @throws SQLException
 */
private long getCounterId(Counter counter, Connection conn) throws SQLException {
    PreparedStatement select = null;
    PreparedStatement insert = null;
    ResultSet rsSelect = null;
    ResultSet rsInsert = null;

    try {
        select = conn.prepareStatement(STMT_SELECT_COUNTER);
        select.setString(1, counter.getName());

        rsSelect = select.executeQuery();

        if (rsSelect.next()) {
            return rsSelect.getLong(1);
        }

        insert = conn.prepareStatement(STMT_INSERT_COUNTER, Statement.RETURN_GENERATED_KEYS);
        insert.setString(1, counter.getName());
        insert.executeUpdate();

        rsInsert = insert.getGeneratedKeys();

        if (!rsInsert.next()) {
            throw new SqoopException(DerbyRepoError.DERBYREPO_0013);
        }

        return rsInsert.getLong(1);
    } finally {
        closeResultSets(rsSelect, rsInsert);
        closeStatements(select, insert);
    }
}

From source file:org.apache.sqoop.repository.derby.DerbyRepositoryHandler.java

/**
 * Resolves counter group database id.//from  ww w  . j av a2 s . c om
 *
 * @param group Given group
 * @param conn Connection to database
 * @return Id
 * @throws SQLException
 */
private long getCounterGroupId(CounterGroup group, Connection conn) throws SQLException {
    PreparedStatement select = null;
    PreparedStatement insert = null;
    ResultSet rsSelect = null;
    ResultSet rsInsert = null;

    try {
        select = conn.prepareStatement(STMT_SELECT_COUNTER_GROUP);
        select.setString(1, group.getName());

        rsSelect = select.executeQuery();

        if (rsSelect.next()) {
            return rsSelect.getLong(1);
        }

        insert = conn.prepareStatement(STMT_INSERT_COUNTER_GROUP, Statement.RETURN_GENERATED_KEYS);
        insert.setString(1, group.getName());
        insert.executeUpdate();

        rsInsert = insert.getGeneratedKeys();

        if (!rsInsert.next()) {
            throw new SqoopException(DerbyRepoError.DERBYREPO_0013);
        }

        return rsInsert.getLong(1);
    } finally {
        closeResultSets(rsSelect, rsInsert);
        closeStatements(select, insert);
    }
}

From source file:org.wso2.carbon.identity.application.mgt.dao.impl.ApplicationDAOImpl.java

/**
 * @param conn//from  w  w w .  java  2  s.c o  m
 * @param tenantId
 * @param idpName
 * @param authenticatorName
 * @param authenticatorDispalyName
 * @return
 * @throws SQLException
 */
private int addAuthenticator(Connection conn, int tenantId, String idpName, String authenticatorName,
        String authenticatorDispalyName) throws SQLException {
    int authenticatorId = -1;
    PreparedStatement prepStmt = null;
    ResultSet rs = null;
    // TENANT_ID, IDP_ID, NAME,IS_ENABLED, DISPLAY_NAME
    String sqlStmt = ApplicationMgtDBQueries.STORE_LOCAL_AUTHENTICATOR;
    try {
        String dbProductName = conn.getMetaData().getDatabaseProductName();
        prepStmt = conn.prepareStatement(sqlStmt,
                new String[] { DBUtils.getConvertedAutoGeneratedColumnName(dbProductName, "ID") });
        prepStmt.setInt(1, tenantId);
        prepStmt.setString(2, CharacterEncoder.getSafeText(idpName));
        prepStmt.setInt(3, tenantId);
        prepStmt.setString(4, CharacterEncoder.getSafeText(authenticatorName));
        prepStmt.setString(5, "1");
        prepStmt.setString(6, CharacterEncoder.getSafeText(authenticatorDispalyName));
        prepStmt.execute();
        rs = prepStmt.getGeneratedKeys();
        if (rs.next()) {
            authenticatorId = rs.getInt(1);
        }
    } finally {
        IdentityApplicationManagementUtil.closeStatement(prepStmt);
    }
    return authenticatorId;
}

From source file:org.apache.sqoop.repository.derby.DerbyRepositoryHandler.java

/**
 * Insert directions: FROM and TO./*from ww  w.  jav  a  2  s  . c  o m*/
 * @param conn
 * @return Map<Direction, Long> direction ID => Direction
 */
protected Map<Direction, Long> insertDirections(Connection conn) {
    // Add directions
    Map<Direction, Long> directionMap = new TreeMap<Direction, Long>();
    PreparedStatement insertDirectionStmt = null;
    try {
        // Insert directions and get IDs.
        for (Direction direction : Direction.values()) {
            insertDirectionStmt = conn.prepareStatement(STMT_INSERT_DIRECTION, Statement.RETURN_GENERATED_KEYS);
            insertDirectionStmt.setString(1, direction.toString());
            if (insertDirectionStmt.executeUpdate() != 1) {
                throw new SqoopException(DerbyRepoError.DERBYREPO_0046,
                        "Could not add directions FROM and TO.");
            }

            ResultSet directionId = insertDirectionStmt.getGeneratedKeys();
            if (directionId.next()) {
                if (LOG.isInfoEnabled()) {
                    LOG.info("Loaded direction: " + directionId.getLong(1));
                }

                directionMap.put(direction, directionId.getLong(1));
            } else {
                throw new SqoopException(DerbyRepoError.DERBYREPO_0047,
                        "Could not get ID of direction " + direction);
            }
        }
    } catch (SQLException e) {
        throw new SqoopException(DerbyRepoError.DERBYREPO_0000, e);
    } finally {
        closeStatements(insertDirectionStmt);
    }

    return directionMap;
}

From source file:org.apache.sqoop.repository.derby.DerbyRepositoryHandler.java

/**
 * We are creating the LINK FORM for HDFS and later it the schema will
 * be renamed to LINK CONFIG//from w  w w .  j  a v a 2s  .  co m
 * NOTE: Should be used only in the upgrade path!
 */
@Deprecated
private Long createHdfsLinkForm(Connection conn, Long connectorId) {
    if (LOG.isTraceEnabled()) {
        LOG.trace("Creating HDFS link.");
    }

    PreparedStatement stmt = null;
    int result;
    try {
        short index = 0;
        stmt = conn.prepareStatement(STMT_INSERT_INTO_FORM, Statement.RETURN_GENERATED_KEYS);
        stmt.setLong(1, connectorId);
        stmt.setString(2, "linkConfig");
        // it could also be set to the deprecated "CONNECTION"
        stmt.setString(3, MConfigType.LINK.name());
        stmt.setShort(4, index);
        result = stmt.executeUpdate();
        if (result != 1) {
            throw new SqoopException(DerbyRepoError.DERBYREPO_0012, Integer.toString(result));
        }
        ResultSet rsetFormId = stmt.getGeneratedKeys();

        if (!rsetFormId.next()) {
            throw new SqoopException(DerbyRepoError.DERBYREPO_0013);
        }

        if (LOG.isTraceEnabled()) {
            LOG.trace("Created HDFS connector link FORM.");
        }
        return rsetFormId.getLong(1);
    } catch (SQLException ex) {
        throw new SqoopException(DerbyRepoError.DERBYREPO_0019, ex);
    } finally {
        closeStatements(stmt);
    }
}

From source file:org.apache.sqoop.repository.common.CommonRepositoryHandler.java

/**
 * {@inheritDoc}//from   w  w  w.  j av a  2 s  .co  m
 */
@Override
public void createSubmission(MSubmission submission, Connection conn) {
    PreparedStatement stmt = null;
    int result;
    try {
        stmt = conn.prepareStatement(crudQueries.getStmtInsertSubmission(), Statement.RETURN_GENERATED_KEYS);
        stmt.setLong(1, submission.getJobId());
        stmt.setString(2, submission.getStatus().name());
        stmt.setString(3, submission.getCreationUser());
        stmt.setTimestamp(4, new Timestamp(submission.getCreationDate().getTime()));
        stmt.setString(5, submission.getLastUpdateUser());
        stmt.setTimestamp(6, new Timestamp(submission.getLastUpdateDate().getTime()));
        stmt.setString(7, submission.getExternalJobId());
        stmt.setString(8, submission.getExternalLink());
        stmt.setString(9, submission.getError().getErrorSummary());
        stmt.setString(10, submission.getError().getErrorDetails());

        result = stmt.executeUpdate();
        if (result != 1) {
            throw new SqoopException(CommonRepositoryError.COMMON_0009, Integer.toString(result));
        }

        ResultSet rsetSubmissionId = stmt.getGeneratedKeys();

        if (!rsetSubmissionId.next()) {
            throw new SqoopException(CommonRepositoryError.COMMON_0010);
        }

        long submissionId = rsetSubmissionId.getLong(1);

        if (submission.getCounters() != null) {
            createSubmissionCounters(submissionId, submission.getCounters(), conn);
        }

        // Save created persistence id
        submission.setPersistenceId(submissionId);

    } catch (SQLException ex) {
        logException(ex, submission);
        throw new SqoopException(CommonRepositoryError.COMMON_0031, ex);
    } finally {
        closeStatements(stmt);
    }
}

From source file:org.apache.sqoop.repository.derby.DerbyRepositoryHandler.java

/**
 * Pre-register Driver since the 1.99.3 release NOTE: This should be used only
 * in the upgrade path/*from  w w  w .j  a  v a2  s  .com*/
 */
@Deprecated
protected long registerDriver(Connection conn) {
    if (LOG.isTraceEnabled()) {
        LOG.trace("Begin Driver loading.");
    }

    PreparedStatement baseDriverStmt = null;
    try {
        baseDriverStmt = conn.prepareStatement(STMT_INSERT_INTO_CONFIGURABLE, Statement.RETURN_GENERATED_KEYS);
        baseDriverStmt.setString(1, MDriver.DRIVER_NAME);
        baseDriverStmt.setString(2, Driver.getClassName());
        baseDriverStmt.setString(3, "1");
        baseDriverStmt.setString(4, MConfigurableType.DRIVER.name());

        int baseDriverCount = baseDriverStmt.executeUpdate();
        if (baseDriverCount != 1) {
            throw new SqoopException(DerbyRepoError.DERBYREPO_0012, Integer.toString(baseDriverCount));
        }

        ResultSet rsetDriverId = baseDriverStmt.getGeneratedKeys();

        if (!rsetDriverId.next()) {
            throw new SqoopException(DerbyRepoError.DERBYREPO_0013);
        }
        return rsetDriverId.getLong(1);
    } catch (SQLException ex) {
        throw new SqoopException(DerbyRepoError.DERBYREPO_0050, ex);
    } finally {
        closeStatements(baseDriverStmt);
    }
}

From source file:org.apache.sqoop.repository.derby.DerbyRepositoryHandler.java

private long insertAndGetDriverId(MDriver mDriver, Connection conn) {
    PreparedStatement baseDriverStmt = null;
    try {// w  w  w  .  java2  s.  co  m
        baseDriverStmt = conn.prepareStatement(STMT_INSERT_INTO_CONFIGURABLE, Statement.RETURN_GENERATED_KEYS);
        baseDriverStmt.setString(1, mDriver.getUniqueName());
        baseDriverStmt.setString(2, Driver.getClassName());
        baseDriverStmt.setString(3, mDriver.getVersion());
        baseDriverStmt.setString(4, mDriver.getType().name());

        int baseDriverCount = baseDriverStmt.executeUpdate();
        if (baseDriverCount != 1) {
            throw new SqoopException(DerbyRepoError.DERBYREPO_0012, Integer.toString(baseDriverCount));
        }

        ResultSet rsetDriverId = baseDriverStmt.getGeneratedKeys();

        if (!rsetDriverId.next()) {
            throw new SqoopException(DerbyRepoError.DERBYREPO_0013);
        }
        return rsetDriverId.getLong(1);
    } catch (SQLException ex) {
        throw new SqoopException(DerbyRepoError.DERBYREPO_0050, mDriver.toString(), ex);
    } finally {
        closeStatements(baseDriverStmt);
    }
}