Example usage for java.sql Statement NO_GENERATED_KEYS

List of usage examples for java.sql Statement NO_GENERATED_KEYS

Introduction

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

Prototype

int NO_GENERATED_KEYS

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

Click Source Link

Document

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

Usage

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

public static PreparedStatement prepare(final Connection conn, final String sql, Object... parameters)
        throws SQLException {
    return prepare(conn, Statement.NO_GENERATED_KEYS, sql, parameters);
}

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

public PreparedStatement prepareStatement(final Connection conn) throws SQLException {
    Assert.argumentNotNull(conn);/*from   w  w w.  ja va  2s  . c  om*/

    return conn.prepareStatement(sql,
            autoGeneratedKeys ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS);
}

From source file:co.marcin.novaguilds.impl.storage.AbstractDatabaseStorage.java

/**
 * Prepares the statements//  ww  w  .  j ava 2 s.  c o m
 */
protected void prepareStatements() {
    try {
        long nanoTime = System.nanoTime();
        LoggerUtils.info("Preparing statements...");
        preparedStatementMap.clear();
        connect();

        int returnKeys = isStatementReturnGeneratedKeysSupported() ? Statement.RETURN_GENERATED_KEYS
                : Statement.NO_GENERATED_KEYS;

        //Guilds insert (id, tag, name, leader, spawn, allies, alliesinv, war, nowarinv, money, points, lives, timerest, lostlive, activity, created, bankloc, slots, openinv)
        String guildsInsertSQL = "INSERT INTO `" + Config.MYSQL_PREFIX.getString()
                + "guilds` VALUES(null,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);";
        PreparedStatement guildsInsert = getConnection().prepareStatement(guildsInsertSQL, returnKeys);
        preparedStatementMap.put(PreparedStatements.GUILDS_INSERT, guildsInsert);

        //Guilds select
        String guildsSelectSQL = "SELECT * FROM `" + Config.MYSQL_PREFIX.getString() + "guilds`";
        PreparedStatement guildsSelect = getConnection().prepareStatement(guildsSelectSQL);
        preparedStatementMap.put(PreparedStatements.GUILDS_SELECT, guildsSelect);

        //Guilds delete
        String guildsDeleteSQL = "DELETE FROM `" + Config.MYSQL_PREFIX.getString() + "guilds` WHERE `id`=?";
        PreparedStatement guildsDelete = getConnection().prepareStatement(guildsDeleteSQL);
        preparedStatementMap.put(PreparedStatements.GUILDS_DELETE, guildsDelete);

        //Guilds update
        String guildsUpdateSQL = "UPDATE `" + Config.MYSQL_PREFIX.getString()
                + "guilds` SET `tag`=?, `name`=?, `leader`=?, `spawn`=?, `allies`=?, `alliesinv`=?, `war`=?, `nowarinv`=?, `money`=?, `points`=?, `lives`=?, `timerest`=?, `lostlive`=?, `activity`=?, `bankloc`=?, `slots`=?, `openinv`=?, `banner`=? WHERE `id`=?";
        PreparedStatement guildsUpdate = getConnection().prepareStatement(guildsUpdateSQL);
        preparedStatementMap.put(PreparedStatements.GUILDS_UPDATE, guildsUpdate);

        //Players insert (id, uuid, name, guild, invitedto, points, kills, deaths)
        String playersInsertSQL = "INSERT INTO `" + Config.MYSQL_PREFIX.getString()
                + "players` VALUES(null,?,?,?,?,?,?,?)";
        PreparedStatement playersInsert = getConnection().prepareStatement(playersInsertSQL, returnKeys);
        preparedStatementMap.put(PreparedStatements.PLAYERS_INSERT, playersInsert);

        //Players select
        String playerSelectSQL = "SELECT * FROM `" + Config.MYSQL_PREFIX.getString() + "players`";
        PreparedStatement playersSelect = getConnection().prepareStatement(playerSelectSQL);
        preparedStatementMap.put(PreparedStatements.PLAYERS_SELECT, playersSelect);

        //Players update
        String playersUpdateSQL = "UPDATE `" + Config.MYSQL_PREFIX.getString()
                + "players` SET `invitedto`=?, `guild`=?, `points`=?, `kills`=?, `deaths`=? WHERE `uuid`=?";
        PreparedStatement playersUpdate = getConnection().prepareStatement(playersUpdateSQL);
        preparedStatementMap.put(PreparedStatements.PLAYERS_UPDATE, playersUpdate);

        //Players delete
        String playersDeleteSQL = "DELETE FROM `" + Config.MYSQL_PREFIX.getString() + "players` WHERE `id`=?";
        PreparedStatement playersDelete = getConnection().prepareStatement(playersDeleteSQL);
        preparedStatementMap.put(PreparedStatements.PLAYERS_DELETE, playersDelete);

        //Regions insert (id, loc_1, loc_2, guild, world)
        String regionsInsertSQL = "INSERT INTO `" + Config.MYSQL_PREFIX.getString()
                + "regions` VALUES(null,?,?,?,?);";
        PreparedStatement regionsInsert = getConnection().prepareStatement(regionsInsertSQL, returnKeys);
        preparedStatementMap.put(PreparedStatements.REGIONS_INSERT, regionsInsert);

        //Regions select
        String regionsSelectSQL = "SELECT * FROM `" + Config.MYSQL_PREFIX.getString() + "regions`";
        PreparedStatement regionsSelect = getConnection().prepareStatement(regionsSelectSQL);
        preparedStatementMap.put(PreparedStatements.REGIONS_SELECT, regionsSelect);

        //Regions delete
        String regionsDeleteSQL = "DELETE FROM `" + Config.MYSQL_PREFIX.getString() + "regions` WHERE `id`=?";
        PreparedStatement regionsDelete = getConnection().prepareStatement(regionsDeleteSQL);
        preparedStatementMap.put(PreparedStatements.REGIONS_DELETE, regionsDelete);

        //Regions update
        String regionsUpdateSQL = "UPDATE `" + Config.MYSQL_PREFIX.getString()
                + "regions` SET `loc_1`=?, `loc_2`=?, `guild`=?, `world`=? WHERE `id`=?";
        PreparedStatement regionsUpdate = getConnection().prepareStatement(regionsUpdateSQL);
        preparedStatementMap.put(PreparedStatements.REGIONS_UPDATE, regionsUpdate);

        //Ranks insert (id, name, guild, permissions, players, default, clone)
        String ranksInsertSQL = "INSERT INTO `" + Config.MYSQL_PREFIX.getString()
                + "ranks` VALUES(null,?,?,?,?,?,?);";
        PreparedStatement ranksInsert = getConnection().prepareStatement(ranksInsertSQL, returnKeys);
        preparedStatementMap.put(PreparedStatements.RANKS_INSERT, ranksInsert);

        //Ranks select
        String ranksSelectSQL = "SELECT * FROM `" + Config.MYSQL_PREFIX.getString() + "ranks`";
        PreparedStatement ranksSelect = getConnection().prepareStatement(ranksSelectSQL);
        preparedStatementMap.put(PreparedStatements.RANKS_SELECT, ranksSelect);

        //Ranks delete
        String ranksDeleteSQL = "DELETE FROM `" + Config.MYSQL_PREFIX.getString() + "ranks` WHERE `id`=?";
        PreparedStatement ranksDelete = getConnection().prepareStatement(ranksDeleteSQL);
        preparedStatementMap.put(PreparedStatements.RANKS_DELETE, ranksDelete);

        //Ranks delete (guild)
        String ranksDeleteGuildSQL = "DELETE FROM `" + Config.MYSQL_PREFIX.getString()
                + "ranks` WHERE `guild`=?";
        PreparedStatement ranksDeleteGuild = getConnection().prepareStatement(ranksDeleteGuildSQL);
        preparedStatementMap.put(PreparedStatements.RANKS_DELETE_GUILD, ranksDeleteGuild);

        //Ranks update
        String ranksUpdateSQL = "UPDATE `" + Config.MYSQL_PREFIX.getString()
                + "ranks` SET `name`=?, `guild`=?, `permissions`=?, `members`=?, `def`=?, `clone`=? WHERE `id`=?";
        PreparedStatement ranksUpdate = getConnection().prepareStatement(ranksUpdateSQL);
        preparedStatementMap.put(PreparedStatements.RANKS_UPDATE, ranksUpdate);

        //Log
        LoggerUtils.info("Statements prepared in "
                + TimeUnit.MILLISECONDS.convert((System.nanoTime() - nanoTime), TimeUnit.NANOSECONDS) / 1000.0
                + "s");
    } catch (SQLException e) {
        LoggerUtils.exception(e);
    }
}

From source file:data.AbstractRepository.java

/**
*
* @param t/*w  w w  .j  a  va2 s . co  m*/
* @throws DataException
*/
@Override
public void save(T t) throws DataException {
    String query;
    int generatedKeys;

    if (t.getId() < 0) {
        query = getInsertQuery(t);
        generatedKeys = Statement.RETURN_GENERATED_KEYS;
    } else {
        query = getUpdateQuery(t);
        generatedKeys = Statement.NO_GENERATED_KEYS;
    }

    Connection connection;
    PreparedStatement statement;
    try {
        connection = DriverManager.getConnection(url, username, password);
        statement = connection.prepareStatement(query, generatedKeys);
        statement.executeUpdate();

        if (t.getId() > 0)
            return;

        ResultSet keys = statement.getGeneratedKeys();

        try {

            if (keys.next()) {
                t.setId(keys.getInt(1));
            }
        } finally {
            keys.close();
            statement.close();
            connection.close();
        }
    } catch (SQLException ex) {
        throw new DataException("Error saving: " + t);
    }
}

From source file:com.adaptris.jdbc.connection.FailoverDatasourceTest.java

@Test
public void testStatements() throws Exception {
    Connection conn = new MyProxy();
    try {// ww  w.ja va  2  s.c om
        try {
            conn.nativeSQL("SELECT * FROM SEQUENCES");
        } catch (Exception e) {

        }
        try {
            conn.createStatement();
        } catch (Exception e) {

        }
        try {
            conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);
        } catch (Exception e) {

        }
        try {
            conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);
        } catch (Exception e) {

        }
        try {
            conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE,
                    ResultSet.CLOSE_CURSORS_AT_COMMIT);
        } catch (Exception e) {

        }
        try {
            conn.prepareStatement("SELECT * FROM SEQUENCES");
        } catch (Exception e) {

        }
        try {
            conn.prepareStatement("SELECT * FROM SEQUENCES", ResultSet.TYPE_FORWARD_ONLY,
                    ResultSet.CONCUR_READ_ONLY);
        } catch (Exception e) {

        }
        try {
            conn.prepareStatement("SELECT * FROM SEQUENCES", ResultSet.TYPE_FORWARD_ONLY,
                    ResultSet.CONCUR_READ_ONLY, ResultSet.CLOSE_CURSORS_AT_COMMIT);
        } catch (Exception e) {

        }
        try {
            conn.prepareStatement("INSERT INTO sequences (id, seq_number) values ('id', 2)",
                    Statement.NO_GENERATED_KEYS);
        } catch (Exception e) {
        }
        try {
            conn.prepareStatement("INSERT INTO sequences (id, seq_number) values ('id', 2)", new int[0]);
        } catch (Exception e) {
        }
        try {
            conn.prepareStatement("INSERT INTO sequences (id, seq_number) values ('id', 2)", new String[0]);
        } catch (Exception e) {

        }

        try {
            conn.prepareCall("SELECT * FROM SEQUENCES");
        } catch (Exception e) {

        }
        try {
            conn.prepareCall("SELECT * FROM SEQUENCES", ResultSet.TYPE_FORWARD_ONLY,
                    ResultSet.CONCUR_READ_ONLY);
        } catch (Exception e) {

        }
        try {
            conn.prepareCall("SELECT * FROM SEQUENCES", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY,
                    ResultSet.CLOSE_CURSORS_AT_COMMIT);
        } catch (Exception e) {

        }
    } finally {
        JdbcUtil.closeQuietly(conn);

    }
}

From source file:com.noelios.restlet.ext.jdbc.JdbcClientHelper.java

/**
 * Helper//from  ww w.j  ava 2  s. c o m
 * 
 * @param connection
 * @param returnGeneratedKeys
 * @param sqlRequests
 * @return the result of the last executed SQL request
 */
private JdbcResult handleSqlRequests(Connection connection, boolean returnGeneratedKeys,
        List<String> sqlRequests) {
    JdbcResult result = null;
    try {
        connection.setAutoCommit(true);
        final Statement statement = connection.createStatement();
        for (final String sqlRequest : sqlRequests) {
            statement.execute(sqlRequest,
                    returnGeneratedKeys ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS);
            result = new JdbcResult(statement);
        }

        // Commit any changes to the database
        if (!connection.getAutoCommit()) {
            connection.commit();
        }
    } catch (SQLException se) {
        getLogger().log(Level.WARNING, "Error while processing the SQL requests", se);
        try {
            if (!connection.getAutoCommit()) {
                connection.rollback();
            }
        } catch (SQLException se2) {
            getLogger().log(Level.WARNING, "Error while rollbacking the transaction", se);
        }
    }
    return result;

}

From source file:edu.pitt.apollo.db.ApolloDbUtils.java

public int addRunDataDescription(String description, String dataFormat, String dataLabel, String dataType,
        String dataSourceSoftware, String dataDestinationSoftware) throws ApolloDatabaseException {
    int runDataDescriptionKey = -1;
    String query = "INSERT INTO run_data_description SET label = ?";

    try (Connection conn = datasource.getConnection()) {

        PreparedStatement pstmt = conn.prepareStatement(query, Statement.NO_GENERATED_KEYS);

        //pstmt.setString(1, description);
        //pstmt.execute();
        //ResultSet rs = pstmt.getGeneratedKeys();
        //if (rs.next()) {
        //    runDataDescriptionKey = rs.getInt(1);
        //}/*from www  . j  a va2s  . com*/
        // query = "INSERT INTO run_data_description_axis_value (run_data_description_id, run_data_description_axis_id, value) values (?,?,?)";
        // pstmt.setInt(1, runDataDescriptionKey);
        // pstmt.setIn
        // not done yet
        return -1;
        //   } catch (ClassNotFoundException ex) {
        //       throw new ApolloDatabaseException("ClassNotFoundException adding run data description ID: " + ex.getMessage());
    } catch (SQLException ex) {
        throw new ApolloDatabaseException("SQLException adding run data description ID: " + ex.getMessage());
    }
}

From source file:org.kawanfw.sql.jdbc.ConnectionHttp.java

/**
 * Creates a default <code>PreparedStatement</code> object that has the
 * capability to retrieve auto-generated keys. The given constant tells the
 * driver whether it should make auto-generated keys available for
 * retrieval. This parameter is ignored if the SQL statement is not an
 * <code>INSERT</code> statement, or an SQL statement able to return
 * auto-generated keys (the list of such statements is vendor-specific).
 * <P>/* ww  w .ja v  a 2 s.  co  m*/
 * <B>Note:</B> This method is optimized for handling parametric SQL
 * statements that benefit from precompilation. If the driver supports
 * precompilation, the method <code>prepareStatement</code> will send the
 * statement to the database for precompilation. Some drivers may not
 * support precompilation. In this case, the statement may not be sent to
 * the database until the <code>PreparedStatement</code> object is executed.
 * This has no direct effect on users; however, it does affect which methods
 * throw certain SQLExceptions.
 * <P>
 * Result sets created using the returned <code>PreparedStatement</code>
 * object will by default be type <code>TYPE_FORWARD_ONLY</code> and have a
 * concurrency level of <code>CONCUR_READ_ONLY</code>. The holdability of
 * the created result sets can be determined by calling
 * {@link #getHoldability}.
 * 
 * @param sql
 *            an SQL statement that may contain one or more '?' IN parameter
 *            placeholders
 * @param autoGeneratedKeys
 *            a flag indicating whether auto-generated keys should be
 *            returned; one of <code>Statement.RETURN_GENERATED_KEYS</code>
 *            or <code>Statement.NO_GENERATED_KEYS</code>
 * @return a new <code>PreparedStatement</code> object, containing the
 *         pre-compiled SQL statement, that will have the capability of
 *         returning auto-generated keys
 * @exception SQLException
 *                if a database access error occurs, this method is called
 *                on a closed connection or the given parameter is not a
 *                <code>Statement</code> constant indicating whether
 *                auto-generated keys should be returned
 * @exception SQLFeatureNotSupportedException
 *                if the JDBC driver does not support this method with a
 *                constant of Statement.RETURN_GENERATED_KEYS
 * @since 1.4
 */
public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {

    if (autoGeneratedKeys != Statement.RETURN_GENERATED_KEYS
            && autoGeneratedKeys != Statement.NO_GENERATED_KEYS) {
        throw new SQLException(
                "Invalid parameter autoGeneratedKeys value. Must be 1 or 2. Valus is: " + autoGeneratedKeys);
    }

    return new PreparedStatementHttp(this, sql, autoGeneratedKeys);

}

From source file:org.openconcerto.sql.model.SQLDataSource.java

/**
 * Execute la requete avec le statement pass. Attention cette mthode ne peut fermer le
 * statement car elle retourne directement le resultSet.
 * //from w w w. jav  a  2s  .  c om
 * @param query le requte  excuter.
 * @param stmt le statement.
 * @return le rsultat de la requte, should never be null according to the spec but Derby don't
 *         care.
 * @throws SQLException si erreur lors de l'excution de la requte.
 */
private ResultSet execute(String query, Statement stmt) throws SQLException, RTInterruptedException {
    // System.err.println("\n" + count + "*** " + query + "\n");

    if (State.DEBUG)
        State.INSTANCE.beginRequest(query);

    // test before calling JDBC methods and creating threads
    boolean interrupted = false;
    if (QUERY_TUNING > 0) {
        try {
            Thread.sleep(QUERY_TUNING);
        } catch (InterruptedException e1) {
            interrupted = true;
        }
    } else {
        interrupted = Thread.currentThread().isInterrupted();
    }
    if (interrupted) {
        throw new RTInterruptedException("request interrupted : " + query);
    }

    final long t1 = System.currentTimeMillis();
    ResultSet rs = null;
    try {
        // MAYBE un truc un peu plus formel
        if (query.startsWith("INSERT") || query.startsWith("UPDATE") || query.startsWith("DELETE")
                || query.startsWith("CREATE") || query.startsWith("ALTER") || query.startsWith("DROP")
                || query.startsWith("SET")) {
            // MS SQL doesn't support UPDATE
            final boolean returnGenK = query.startsWith("INSERT")
                    && stmt.getConnection().getMetaData().supportsGetGeneratedKeys();
            stmt.executeUpdate(query,
                    returnGenK ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS);
            rs = returnGenK ? stmt.getGeneratedKeys() : null;
        } else {
            // TODO en faire qu'un seul par Connection
            final ExecutorThread thr = new ExecutorThread(stmt, query);
            // on lance l'excution
            thr.start();
            // et on attend soit qu'elle finisse soit qu'on soit interrompu
            try {
                rs = thr.getRs();
            } catch (InterruptedException e) {
                thr.stopQuery();
                throw new InterruptedQuery("request interrupted : " + query, e, thr);
            }
        }
    } finally {
        if (State.DEBUG)
            State.INSTANCE.endRequest(query);
    }
    long t2 = System.currentTimeMillis();
    // obviously very long queries tend to last longer, that's normal so don't warn
    if (t2 - t1 > 1000 && query.length() < 1000) {
        System.err.println("Warning:" + (t2 - t1) + "ms pour :" + query);
    }

    count++;
    return rs;
}

From source file:org.primeframework.persistence.jdbc.Insert.java

/**
 * Performs the insert.//from  w ww  .  j  av a2 s .  c o  m
 *
 * @return The number of rows inserted.
 * @throws InsertException If the insert fails.
 */
public int go() throws InsertException {
    PreparedStatement ps = null;
    try {
        ps = c.prepareStatement(sql.toString(), Statement.NO_GENERATED_KEYS);
        setParams(ps);

        return ps.executeUpdate();
    } catch (SQLException e) {
        throw new InsertException(e);
    } finally {
        close(ps);
    }
}