Example usage for java.sql Statement RETURN_GENERATED_KEYS

List of usage examples for java.sql Statement RETURN_GENERATED_KEYS

Introduction

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

Prototype

int RETURN_GENERATED_KEYS

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

Click Source Link

Document

The constant indicating that generated keys should be made available for retrieval.

Usage

From source file:com.taobao.tdhs.jdbc.TDHSStatement.java

public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException {
    if (autoGeneratedKeys == Statement.RETURN_GENERATED_KEYS) {
        throw new SQLFeatureNotSupportedException();
    }//from  www .  java  2s .  com
    return executeUpdate(sql);
}

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

protected long insertWithGeneratedKey(Connection conn, String sql, String column, String sequenceName,
        Object[] args, int[] types) throws SQLException {
    long key = 0;
    PreparedStatement ps = null;/*from   w  w w  . j a  v  a  2  s .c  o m*/
    try {
        boolean supportsGetGeneratedKeys = supportsGetGeneratedKeys();
        boolean supportsReturningKeys = supportsReturningKeys();
        if (allowsNullForIdentityColumn()) {
            if (supportsGetGeneratedKeys) {
                ps = conn.prepareStatement(sql, new int[] { 1 });
            } else if (supportsReturningKeys) {
                ps = conn.prepareStatement(sql + " returning " + column);
            } else {
                ps = conn.prepareStatement(sql);
            }
        } else {
            String replaceSql = sql.replaceFirst("\\([\"|\\w]*,", "(").replaceFirst("\\(null,", "(");
            if (supportsGetGeneratedKeys) {
                ps = conn.prepareStatement(replaceSql, Statement.RETURN_GENERATED_KEYS);
            } else {
                ps = conn.prepareStatement(replaceSql);
            }
        }
        ps.setQueryTimeout(settings.getQueryTimeout());
        setValues(ps, args, types, lobHandler.getDefaultHandler());

        ResultSet rs = null;
        if (supportsGetGeneratedKeys) {
            ps.execute();
            try {
                rs = ps.getGeneratedKeys();
                if (rs.next()) {
                    key = rs.getLong(1);
                }
            } finally {
                close(rs);
            }
        } else if (supportsReturningKeys) {
            try {
                rs = ps.executeQuery();
                if (rs.next()) {
                    key = rs.getLong(1);
                }
            } finally {
                close(rs);
            }
        } else {
            Statement st = null;
            ps.execute();
            try {
                st = conn.createStatement();
                rs = st.executeQuery(getSelectLastInsertIdSql(sequenceName));
                if (rs.next()) {
                    key = rs.getLong(1);
                }
            } finally {
                close(rs);
                close(st);
            }
        }
    } finally {
        close(ps);
    }
    return key;
}

From source file:dk.netarkivet.harvester.datamodel.DomainDBDAO.java

/**
 * Insert new owner info for a domain.//from www .ja  v  a  2s.  co  m
 * @param c 
 *            A connection to the database
 * @param d
 *            A domain to insert on. The domains ID must be correct.
 * @param doi
 *            Owner info to insert.
 * @throws SQLException
 *             If any database problems occur during the insertion process.
 */
private void insertOwnerInfo(Connection c, Domain d, DomainOwnerInfo doi) throws SQLException {
    PreparedStatement s = c.prepareStatement(
            "INSERT INTO ownerinfo " + "( domain_id, created, info ) VALUES ( ?, ?, ?)",
            Statement.RETURN_GENERATED_KEYS);
    s.setLong(1, d.getID());
    s.setTimestamp(2, new Timestamp(doi.getDate().getTime()));
    s.setString(3, doi.getInfo());
    s.executeUpdate();
    doi.setID(DBUtils.getGeneratedID(s));
}

From source file:org.bidtime.dbutils.QueryRunnerEx.java

/**
 * Executes the given batch of INSERT SQL statements.
 * @param conn The connection to use for the query call.
 * @param closeConn True if the connection should be closed, false otherwise.
 * @param sql The SQL statement to execute.
 * @param rsh The handler used to create the result object from
 * the <code>ResultSet</code> of auto-generated keys.
 * @param params The query replacement parameters.
 * @return The result generated by the handler.
 * @throws SQLException If there are database or parameter errors.
 * @since 1.6//from   w  w w . j  a  va  2  s  . co m
 */
private <T> T insertBatch(Connection conn, boolean closeConn, String sql, ResultSetHandler<T> rsh,
        Object[][] params) throws SQLException {
    if (conn == null) {
        throw new SQLException("Null connection");
    }

    if (sql == null) {
        if (closeConn) {
            close(conn);
        }
        throw new SQLException("Null SQL statement");
    }

    if (params == null) {
        if (closeConn) {
            close(conn);
        }
        throw new SQLException("Null parameters. If parameters aren't need, pass an empty array.");
    }

    PreparedStatement stmt = null;
    long startTime = System.currentTimeMillis();
    T generatedKeys = null;
    try {
        stmt = this.prepareStatement(conn, sql, Statement.RETURN_GENERATED_KEYS);
        stmt.setQueryTimeout(StmtParams.getInstance().getStmtBatchTimeOut());

        for (int i = 0; i < params.length; i++) {
            this.fillStatement(stmt, params[i]);
            stmt.addBatch();
        }
        stmt.executeBatch();
        ResultSet rs = stmt.getGeneratedKeys();
        generatedKeys = rsh.handle(rs);
    } catch (SQLException e) {
        this.rethrow(e, sql, (Object[]) params);
    } finally {
        close(stmt);
        if (closeConn) {
            close(conn);
        }
        if (LogInsertSql.logInfoOrDebug()) {
            LogInsertSql.logFormatTimeNow(startTime, sql, params);
        }
    }
    return generatedKeys;
}

From source file:com.taobao.tdhs.jdbc.TDHSStatement.java

public boolean execute(String sql, int autoGeneratedKeys) throws SQLException {
    if (autoGeneratedKeys == Statement.RETURN_GENERATED_KEYS) {
        throw new SQLFeatureNotSupportedException();
    }//from  w w  w  .  ja  v  a2s .  c  o  m
    return execute(sql);
}

From source file:de.innovationgate.webgate.api.jdbc.custom.JDBCSource.java

private PreparedStatement getInsertStatement(String folder, Map values) throws SQLException {

    if (!_tables.containsKey(folder.toLowerCase())) {
        return null;
    }/*from   www.  j  a  v  a  2 s.c  om*/

    // Prepare statement
    StringBuffer query = new StringBuffer();
    query.append("INSERT INTO " + folder);

    List columnNames = new ArrayList(values.keySet());
    query.append(" (").append(WGUtils.serializeCollection(columnNames, ",")).append(")");

    List columnValues = Collections.nCopies(columnNames.size(), "?");
    query.append(" VALUES (").append(WGUtils.serializeCollection(columnValues, ",")).append(")");

    PreparedStatement stmt = getConnection().prepareStatement(query.toString(),
            Statement.RETURN_GENERATED_KEYS);

    // Insert parameter values
    for (int idx = 0; idx < columnNames.size(); idx++) {
        String column = (String) columnNames.get(idx);
        stmt.setObject(idx + 1, values.get(column));
    }

    return stmt;
}

From source file:dk.netarkivet.harvester.datamodel.DomainDBDAO.java

/**
 * Insert new seedlist for a domain./*w w  w . ja  v  a 2s .c  o  m*/
 * @param c 
 *            A connection to the database
 * @param d
 *            A domain to insert on. The domains ID must be correct.
 * @param sl
 *            Seedlist to insert.
 * @throws SQLException
 *             If some database error occurs during the insertion process.
 */
private void insertSeedlist(Connection c, Domain d, SeedList sl) throws SQLException {
    PreparedStatement s = c.prepareStatement(
            "INSERT INTO seedlists " + "( name, comments, domain_id, seeds ) " + "VALUES ( ?, ?, ?, ? )",
            Statement.RETURN_GENERATED_KEYS);
    // ID is autogenerated
    DBUtils.setName(s, 1, sl, Constants.MAX_NAME_SIZE);
    DBUtils.setComments(s, 2, sl, Constants.MAX_COMMENT_SIZE);
    s.setLong(3, d.getID());
    DBUtils.setClobMaxLength(s, 4, sl.getSeedsAsString(), Constants.MAX_SEED_LIST_SIZE, sl, "seedlist");
    s.executeUpdate();
    sl.setID(DBUtils.getGeneratedID(s));
}

From source file:dk.netarkivet.harvester.datamodel.DomainDBDAO.java

/**
 * Inserts a new password entry into the database.
 * @param c /*from ww w. j  a  va2  s  .  co  m*/
 *            A connection to the database
 * @param d
 *            A domain to insert on. The domains ID must be correct.
 * @param p
 *            A password entry to insert.
 * @throws SQLException
 *             If some database error occurs during the insertion process.
 */
private void insertPassword(Connection c, Domain d, Password p) throws SQLException {
    PreparedStatement s = c
            .prepareStatement(
                    "INSERT INTO passwords " + "( name, comments, domain_id, url, realm, username, "
                            + "password ) " + "VALUES ( ?, ?, ?, ?, ?, ?, ? )",
                    Statement.RETURN_GENERATED_KEYS);
    // ID is autogenerated
    DBUtils.setName(s, 1, p, Constants.MAX_NAME_SIZE);
    DBUtils.setComments(s, 2, p, Constants.MAX_COMMENT_SIZE);
    s.setLong(3, d.getID());
    DBUtils.setStringMaxLength(s, 4, p.getPasswordDomain(), Constants.MAX_URL_SIZE, p, "password url");
    DBUtils.setStringMaxLength(s, 5, p.getRealm(), Constants.MAX_REALM_NAME_SIZE, p, "password realm");
    DBUtils.setStringMaxLength(s, 6, p.getUsername(), Constants.MAX_USER_NAME_SIZE, p, "password username");
    DBUtils.setStringMaxLength(s, 7, p.getPassword(), Constants.MAX_PASSWORD_SIZE, p, "password");
    s.executeUpdate();
    p.setID(DBUtils.getGeneratedID(s));
}

From source file:com.jabyftw.lobstercraft.player.PlayerHandlerService.java

/**
 * Kick or ban player, online or not. This won't announce to the server and will keep a record on MySQL. This method <b>SHOULD</b> run asynchronously.
 *
 * @param offlinePlayer  player to be kicked
 * @param banType        kick type/*from   ww w  .  j a  va 2s  .  c o  m*/
 * @param reason         reason to be at record, from 4 to 120 characters
 * @param moderatorId    moderator to be stored, can be null
 * @param bannedDuration ban duration, can be null
 * @return a ban response to the CommandSender
 */
public BanResponse kickPlayer(@NotNull OfflinePlayer offlinePlayer, @NotNull final BanType banType,
        @NotNull final String reason, @Nullable Integer moderatorId, @Nullable final Long bannedDuration) {
    // Check if player is registered
    if (!offlinePlayer.isRegistered())
        return BanResponse.PLAYER_NOT_REGISTERED;

    // Set variables
    int playerId = offlinePlayer.getPlayerId();
    long recordDate = System.currentTimeMillis();

    // Check unban date
    Long unbanDate;
    if (banType != BanType.PLAYER_TEMPORARILY_BANNED) // Only temporary banned requires this argument
        unbanDate = null;
    else if (bannedDuration != null)
        unbanDate = recordDate + bannedDuration;
    else
        return BanResponse.BAN_DURATION_NOT_SET;

    // Check if reason has right size
    if (!Util.checkStringLength(reason, 4, 120))
        return BanResponse.INVALID_REASON_LENGTH;

    try {
        // Retrieve connection
        Connection connection = LobsterCraft.dataSource.getConnection();

        // Prepare statement
        PreparedStatement preparedStatement = connection.prepareStatement(
                // 6 arguments
                "INSERT INTO `minecraft`.`ban_records` (`user_playerId`, `user_moderatorId`, `banType`, `recordDate`, `reason`, `unbanDate`) VALUES (?, ?, ?, ?, ?, ?);",
                Statement.RETURN_GENERATED_KEYS);

        // Set variables for query
        preparedStatement.setInt(1, playerId);
        preparedStatement.setObject(2, moderatorId, Types.INTEGER); // will write null if is null
        preparedStatement.setByte(3, banType.getTypeId());
        preparedStatement.setLong(4, recordDate);
        preparedStatement.setString(5, reason);
        preparedStatement.setObject(6, unbanDate, Types.BIGINT);

        // Execute statement
        preparedStatement.execute();

        // Retrieve generated keys
        ResultSet generatedKeys = preparedStatement.getGeneratedKeys();

        // Throw error if there is no generated key
        if (!generatedKeys.next())
            throw new SQLException("There is no generated key");

        // Create entry
        BannedPlayerEntry bannedPlayerEntry = new BannedPlayerEntry(generatedKeys.getLong("recordId"),
                moderatorId, banType, recordDate, reason, unbanDate);

        // Add entry to storage
        synchronized (playerBanEntries) {
            playerBanEntries.putIfAbsent(playerId, new HashSet<>());
            playerBanEntries.get(playerId).add(bannedPlayerEntry);
        }

        // Close everything
        generatedKeys.close();
        preparedStatement.close();
        connection.close();

        // Schedule player kick, if he is online
        OnlinePlayer onlinePlayer = offlinePlayer.getOnlinePlayer(null);
        if (onlinePlayer != null)
            Bukkit.getServer().getScheduler().runTask(LobsterCraft.plugin, () -> {
                if (onlinePlayer.getPlayer().isOnline())
                    // Kick player if he is online
                    onlinePlayer.getPlayer().kickPlayer(bannedPlayerEntry.getKickMessage());
            });

        return BanResponse.SUCCESSFULLY_EXECUTED;
    } catch (SQLException exception) {
        exception.printStackTrace();
        return BanResponse.ERROR_OCCURRED;
    }
}

From source file:org.apache.ctakes.ytex.uima.mapper.DocumentMapperServiceImpl.java

private BiMap<Annotation, Integer> saveAnnoBase(final JCas jcas, final Set<String> setTypesToIgnore,
        final int docId) {
    final AnnotationIndex<Annotation> annoIdx = jcas.getAnnotationIndex(Annotation.typeIndexID);
    final List<Annotation> listAnno = new ArrayList<Annotation>(annoIdx.size());
    final BiMap<Annotation, Integer> mapAnnoToId = HashBiMap.create();
    final FSIterator<Annotation> annoIterator = annoIdx.iterator();
    this.sessionFactory.getCurrentSession().doWork(new Work() {

        @Override/*from  ww w  . j  a  v  a2  s  . c  o  m*/
        public void execute(Connection conn) throws SQLException {
            PreparedStatement ps = null;
            ResultSet rs = null;
            try {
                ps = conn.prepareStatement("insert into " + getTablePrefix()
                        + "anno_base (document_id, span_begin, span_end, uima_type_id) values (?, ?, ?, ?)",
                        Statement.RETURN_GENERATED_KEYS);
                while (annoIterator.hasNext()) {
                    Annotation anno = (Annotation) annoIterator.next();
                    String annoClass = anno.getClass().getName();
                    if (!setTypesToIgnore.contains(annoClass) && uimaTypeMap.containsKey(annoClass)) {
                        // should not ignore, and we know how to map this
                        // annotation
                        listAnno.add(anno);
                        ps.setInt(1, docId);
                        ps.setInt(2, anno.getBegin());
                        ps.setInt(3, anno.getEnd());
                        ps.setInt(4, uimaTypeMap.get(annoClass).getUimaTypeID());
                        ps.addBatch();
                    }
                }
                ps.executeBatch();
                rs = ps.getGeneratedKeys();
                int annoIndex = 0;
                while (rs.next()) {
                    mapAnnoToId.put(listAnno.get(annoIndex), rs.getInt(1));
                    annoIndex++;
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            } finally {
                if (rs != null) {
                    try {
                        rs.close();
                    } catch (SQLException e) {
                    }
                }
                if (ps != null) {
                    try {
                        ps.close();
                    } catch (SQLException e) {
                    }
                }
            }
        }
    });
    return mapAnnoToId;
}