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:com.keybox.manage.db.SystemDB.java

/**
 * inserts host system into DB//from   w ww .  jav a  2s.co m
 *
 * @param hostSystem host system object
 * @return user id
 */
public static Long insertSystem(HostSystem hostSystem) {

    Connection con = null;

    Long userId = null;
    try {
        con = DBUtils.getConn();
        PreparedStatement stmt = con.prepareStatement(
                "insert into system (display_nm, user, host, port, authorized_keys, status_cd) values (?,?,?,?,?,?)",
                PreparedStatement.RETURN_GENERATED_KEYS);
        stmt.setString(1, hostSystem.getDisplayNm());
        stmt.setString(2, hostSystem.getUser());
        stmt.setString(3, hostSystem.getHost());
        stmt.setInt(4, hostSystem.getPort());
        stmt.setString(5, hostSystem.getAuthorizedKeys());
        stmt.setString(6, hostSystem.getStatusCd());
        stmt.execute();

        ResultSet rs = stmt.getGeneratedKeys();
        if (rs.next()) {
            userId = rs.getLong(1);
        }
        DBUtils.closeStmt(stmt);

    } catch (Exception e) {
        log.error(e.toString(), e);
    }
    DBUtils.closeConn(con);
    return userId;

}

From source file:Emporium.Controle.ContrDestinatarioImporta.java

public static int inserir(int idCliente, int idDepartamento, String nome, String cpf_cnpj, String empresa,
        String cep, String endereco, String numero, String complemento, String bairro, String cidade, String uf,
        String email, String celular, String pais, String nomeBD, String tags) {
    Connection conn = Conexao.conectar(nomeBD);
    String sql = "INSERT INTO cliente_destinatario (idCliente, nome, cpf_cnpj, empresa, cep, endereco, numero, complemento, bairro, cidade, uf, email, celular, pais, tags, idDepartamento) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
    //System.out.println("inserir Destinatario -----------------\n"+sql+"\n---------------");

    try {//from   w  ww. j  a v  a2 s  .c o m
        PreparedStatement valores = conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
        valores.setInt(1, idCliente);
        valores.setString(2, FormataString.removeSpecialChars(nome));
        valores.setString(3, cpf_cnpj);
        valores.setString(4, empresa);
        valores.setString(5, cep);
        valores.setString(6, FormataString.removeSpecialChars(endereco));
        valores.setString(7, numero);
        valores.setString(8, complemento);
        valores.setString(9, bairro);
        valores.setString(10, cidade);
        valores.setString(11, uf);
        valores.setString(12, email);
        valores.setString(13, celular);
        valores.setString(14, pais);
        valores.setString(15, tags);
        valores.setInt(16, idDepartamento);
        valores.executeUpdate();
        int autoIncrementKey = 0;
        ResultSet rs = valores.getGeneratedKeys();
        if (rs.next()) {
            autoIncrementKey = rs.getInt(1);
        }
        valores.close();
        return autoIncrementKey;
    } catch (SQLException e) {
        //System.out.println("ERRO > "+e);
        ContrErroLog.inserir("HOITO - ContrPreVendaDest.inserir", "SQLException", sql, e.toString());
        return 0;
    } finally {
        Conexao.desconectar(conn);
    }
}

From source file:io.kahu.hawaii.util.call.sql.response.UpdateIdResponseHandler.java

@Override
public void addToResponse(PreparedStatement payload, Response<Long> response) throws ServerException {
    try {/*from   w  w w .j  a v a 2s . c om*/
        ResultSet keys = payload.getGeneratedKeys();
        if (keys != null) {
            try {
                keys.next();
                Long keyValue = keys.getLong(1);
                response.set(keyValue);
            } finally {
                JdbcUtils.closeResultSet(keys);
            }
        }
    } catch (SQLException e) {
        response.setStatus(ResponseStatus.BACKEND_FAILURE, e);
    }
}

From source file:opengovcrawler.DB.java

/**
 * Starts the crawler's activity log//from www. j  av a2s . co  m
 *
 * @param startTime - The start time of the crawling procedure
 * @return - The activity's log id
 * @throws java.sql.SQLException
 */
public static int LogCrawler(long startTime) throws SQLException {
    String insertLogSql = "INSERT INTO log.activities (module_id, start_date, end_date, status_id, message) VALUES (?,?,?,?,?)";
    PreparedStatement prepLogCrawlStatement = connection.prepareStatement(insertLogSql,
            Statement.RETURN_GENERATED_KEYS);
    prepLogCrawlStatement.setInt(1, 1);
    prepLogCrawlStatement.setTimestamp(2, new java.sql.Timestamp(startTime));
    prepLogCrawlStatement.setTimestamp(3, null);
    prepLogCrawlStatement.setInt(4, 1);
    prepLogCrawlStatement.setString(5, null);
    prepLogCrawlStatement.executeUpdate();
    ResultSet rsq = prepLogCrawlStatement.getGeneratedKeys();
    int crawlerId = 0;
    if (rsq.next()) {
        crawlerId = rsq.getInt(1);
    }
    prepLogCrawlStatement.close();
    return crawlerId;
}

From source file:org.tec.webapp.jdbc.entity.support.IdentifierCallback.java

/** {@inheritDoc} */
@Override()/* w  ww . j  a  v a  2 s  . c o m*/
public Long doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
    ResultSet generatedKeys = null;
    try {
        ps.execute();

        generatedKeys = ps.getGeneratedKeys();

        if (generatedKeys.next()) {
            return Long.valueOf(generatedKeys.getLong(1));
        } else {
            throw new SQLException("Unable to insert new record " + ps.toString());
        }
    } finally {
        if (generatedKeys != null) {
            generatedKeys.close();
        }
    }
}

From source file:opengovcrawler.DB.java

/**
 * Insert articles into DB/*  w w  w  .j a v  a  2 s .c o  m*/
 *
 * @param a - The article to be stored
 * @param consID - The consultation's id the the article refers to
 * @return - Returns the article id
 * @throws java.sql.SQLException
 */
public static int InsertArticles(Article a, int consID) throws SQLException {
    // First check if article is already into db. (Consultation might be green and we crawl for new comments,
    // so articles might already exist in the db)
    String selectArticleSql = "SELECT id FROM articles WHERE consultation_id = ? AND title = ?";
    PreparedStatement preparedStatement = connection.prepareStatement(selectArticleSql);
    preparedStatement.setInt(1, consID);
    preparedStatement.setString(2, a.title);
    ResultSet result = preparedStatement.executeQuery();
    int articleID = -1;
    if (result.next()) {
        articleID = result.getInt(1);
    } else {
        String insertArticleSql = "INSERT INTO articles (consultation_id, title, body, art_order, comment_num) VALUES (?,?,?,?,?)";
        PreparedStatement prepInsertStatement = connection.prepareStatement(insertArticleSql,
                Statement.RETURN_GENERATED_KEYS);
        prepInsertStatement.setInt(1, consID);
        prepInsertStatement.setString(2, a.title);
        prepInsertStatement.setString(3, a.content);
        prepInsertStatement.setInt(4, a.order);
        prepInsertStatement.setInt(5, a.numOfComments);
        prepInsertStatement.executeUpdate();
        ResultSet rsq = prepInsertStatement.getGeneratedKeys();
        if (rsq.next()) {
            articleID = rsq.getInt(1);
        }
        prepInsertStatement.close();
    }
    preparedStatement.close();
    return articleID;
}

From source file:com.tethrnet.manage.db.UserDB.java

/**
 * inserts new user//from w  w w .j av  a2 s .co  m
 * 
 * @param con DB connection 
 * @param user user object
 */
public static Long insertUser(Connection con, User user) {

    Long userId = null;

    try {
        PreparedStatement stmt = con.prepareStatement(
                "insert into users (email, username, auth_type, user_type, password, salt) values (?,?,?,?,?,?)",
                Statement.RETURN_GENERATED_KEYS);
        stmt.setString(1, user.getEmail());
        stmt.setString(2, user.getUsername());
        stmt.setString(3, user.getAuthType());
        stmt.setString(4, user.getUserType());
        if (StringUtils.isNotEmpty(user.getPassword())) {
            String salt = EncryptionUtil.generateSalt();
            stmt.setString(5, EncryptionUtil.hash(user.getPassword() + salt));
            stmt.setString(6, salt);
        } else {
            stmt.setString(5, null);
            stmt.setString(6, null);
        }
        stmt.execute();
        ResultSet rs = stmt.getGeneratedKeys();
        if (rs != null && rs.next()) {
            userId = rs.getLong(1);
        }
        DBUtils.closeStmt(stmt);

    } catch (Exception e) {
        log.error(e.toString(), e);
    }

    return userId;

}

From source file:net.paoding.rose.jade.provider.jdbctemplate.PreparedStatementCallbackReturnId.java

@Override
public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {

    if (setter != null) {
        setter.setValues(ps);/*from   w  ww  .  j a v  a2s.co  m*/
    }

    ps.executeUpdate();

    ResultSet keys = ps.getGeneratedKeys();
    if (keys != null) {

        try {
            RowMapperResultSetExtractor extractor = new RowMapperResultSetExtractor(
                    new SingleColumnRowMapper(Number.class), 1);
            return DataAccessUtils.requiredSingleResult((List<?>) extractor.extractData(keys));
        } finally {
            JdbcUtils.closeResultSet(keys);
        }
    }

    return null;
}

From source file:com.sf.ddao.ops.InsertAndGetGeneratedKeySqlOperation.java

public boolean execute(Context context) throws Exception {
    try {//from   w  w  w.j  a  v  a 2 s  .co m
        final MethodCallCtx callCtx = CtxHelper.get(context, MethodCallCtx.class);
        PreparedStatement preparedStatement = statementFactory.createStatement(context, true);
        Object res = null;
        preparedStatement.executeUpdate();
        ResultSet resultSet = preparedStatement.getGeneratedKeys();
        if (resultSet.next()) {
            if (method.getReturnType() == Integer.TYPE || method.getReturnType() == Integer.class) {
                res = resultSet.getInt(1);
            } else if (method.getReturnType() == Long.TYPE || method.getReturnType() == Long.class) {
                res = resultSet.getLong(1);
            } else if (method.getReturnType() == BigDecimal.class) {
                res = resultSet.getBigDecimal(1);
            }
        }
        resultSet.close();
        preparedStatement.close();
        callCtx.setLastReturn(res);
        return CONTINUE_PROCESSING;
    } catch (Exception t) {
        throw new DaoException("Failed to execute sql operation for " + method, t);
    }
}

From source file:org.kawanfw.test.api.client.autogeneratedkeys.InsertPrepStatementAutoKeysTest.java

/**
 * Do a 100 row insert inside a loop/*from w w w . j a va  2s  .c o  m*/
 * 
 * @param connection
 *            the AceQL Connection
 * 
 * @throws Exception
 *             it any Exception occurs
 */
public static void insertPrepStatementExecuteUpdate(Connection connection, int valueToInsert,
        boolean useRawExecute, boolean autoCommitOn) throws Exception {
    // We can now use our Remote JDBC Connection as a regular Connection!

    long maxCustomerId = InsertStatementTestAutoKeysTest.getMaxCustomerId(connection);
    MessageDisplayer.display("");
    MessageDisplayer.display("maxCustomerId: " + maxCustomerId);

    if (!autoCommitOn) {
        connection.setAutoCommit(false);
    }

    // We will do all our remote insert in a SQL Transaction
    try {
        // 1) First create a Customer
        String sql = "insert into customer_auto (customer_title, fname, lname, addressline, town, zipcode, phone) "
                + " values ( ?, ?, ?, ?, ?, ?, ? )";

        MessageDisplayer.display("");
        MessageDisplayer.display("Inserting " + valueToInsert + " customers...");

        PreparedStatement prepStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);

        int i = valueToInsert;
        int j = 1;
        prepStatement.setString(j++, "Sir");
        prepStatement.setNull(j++, Types.VARCHAR);
        prepStatement.setString(j++, "Smith_" + i);
        prepStatement.setString(j++, i + ", Csar Avenue");
        prepStatement.setString(j++, "JavaLand_" + i);
        prepStatement.setString(j++, i + "45");
        prepStatement.setString(j++, i + "-12345678");

        int rc = -1;

        if (!useRawExecute) {
            rc = prepStatement.executeUpdate();
            MessageDisplayer.display("after executeUpdate(): row count: " + rc);

        } else {
            prepStatement.execute();

            rc = prepStatement.getUpdateCount();
            MessageDisplayer.display("after execute(): prepStatement.getUpdateCount(): " + rc);
        }

        if (!autoCommitOn) {
            connection.commit();
        }

        ResultSet keys = prepStatement.getGeneratedKeys();

        long lastKey = -1;
        while (keys.next()) {
            lastKey = keys.getLong(1);
        }
        keys.close();

        MessageDisplayer.display("Last Key: " + lastKey);

        // Don't know why: there is a bug in some engines....
        // Assert.assertEquals("last key = maxCustomerId + 1", lastKey,
        // maxCustomerId + 1);

        // So do another test:
        Assert.assertEquals("last key >= 1", true, lastKey >= 1);

        prepStatement.close();

    } catch (Exception e) {
        e.printStackTrace();

        if (!autoCommitOn) {
            connection.rollback();
        }

        throw e;
    } finally {
        if (!autoCommitOn) {
            connection.setAutoCommit(true);
        }

    }

}