Example usage for org.springframework.jdbc.support JdbcUtils closeStatement

List of usage examples for org.springframework.jdbc.support JdbcUtils closeStatement

Introduction

In this page you can find the example usage for org.springframework.jdbc.support JdbcUtils closeStatement.

Prototype

public static void closeStatement(@Nullable Statement stmt) 

Source Link

Document

Close the given JDBC Statement and ignore any thrown exception.

Usage

From source file:org.springframework.jdbc.core.simple.AbstractJdbcInsert.java

/**
 * Delegate method to execute the insert, generating any number of keys.
 *///from w  w  w .  j  av a2  s .com
private KeyHolder executeInsertAndReturnKeyHolderInternal(final List<?> values) {
    if (logger.isDebugEnabled()) {
        logger.debug("The following parameters are used for call " + getInsertString() + " with: " + values);
    }
    final KeyHolder keyHolder = new GeneratedKeyHolder();

    if (this.tableMetaDataContext.isGetGeneratedKeysSupported()) {
        getJdbcTemplate().update(con -> {
            PreparedStatement ps = prepareStatementForGeneratedKeys(con);
            setParameterValues(ps, values, getInsertTypes());
            return ps;
        }, keyHolder);
    }

    else {
        if (!this.tableMetaDataContext.isGetGeneratedKeysSimulated()) {
            throw new InvalidDataAccessResourceUsageException(
                    "The getGeneratedKeys feature is not supported by this database");
        }
        if (getGeneratedKeyNames().length < 1) {
            throw new InvalidDataAccessApiUsageException("Generated Key Name(s) not specified. "
                    + "Using the generated keys features requires specifying the name(s) of the generated column(s)");
        }
        if (getGeneratedKeyNames().length > 1) {
            throw new InvalidDataAccessApiUsageException(
                    "Current database only supports retrieving the key for a single column. There are "
                            + getGeneratedKeyNames().length + " columns specified: "
                            + Arrays.asList(getGeneratedKeyNames()));
        }

        Assert.state(getTableName() != null, "No table name set");
        final String keyQuery = this.tableMetaDataContext.getSimulationQueryForGetGeneratedKey(getTableName(),
                getGeneratedKeyNames()[0]);
        Assert.state(keyQuery != null, "Query for simulating get generated keys can't be null");

        // This is a hack to be able to get the generated key from a database that doesn't support
        // get generated keys feature. HSQL is one, PostgreSQL is another. Postgres uses a RETURNING
        // clause while HSQL uses a second query that has to be executed with the same connection.

        if (keyQuery.toUpperCase().startsWith("RETURNING")) {
            Long key = getJdbcTemplate().queryForObject(getInsertString() + " " + keyQuery,
                    values.toArray(new Object[values.size()]), Long.class);
            Map<String, Object> keys = new HashMap<>(1);
            keys.put(getGeneratedKeyNames()[0], key);
            keyHolder.getKeyList().add(keys);
        } else {
            getJdbcTemplate().execute((ConnectionCallback<Object>) con -> {
                // Do the insert
                PreparedStatement ps = null;
                try {
                    ps = con.prepareStatement(getInsertString());
                    setParameterValues(ps, values, getInsertTypes());
                    ps.executeUpdate();
                } finally {
                    JdbcUtils.closeStatement(ps);
                }
                //Get the key
                Statement keyStmt = null;
                ResultSet rs = null;
                Map<String, Object> keys = new HashMap<>(1);
                try {
                    keyStmt = con.createStatement();
                    rs = keyStmt.executeQuery(keyQuery);
                    if (rs.next()) {
                        long key = rs.getLong(1);
                        keys.put(getGeneratedKeyNames()[0], key);
                        keyHolder.getKeyList().add(keys);
                    }
                } finally {
                    JdbcUtils.closeResultSet(rs);
                    JdbcUtils.closeStatement(keyStmt);
                }
                return null;
            });
        }
    }

    return keyHolder;
}

From source file:org.springframework.jdbc.support.DatabaseStartupValidator.java

/**
 * Check whether the validation query can be executed on a Connection
 * from the specified DataSource, with the specified interval between
 * checks, until the specified timeout./*  w  w w  .j a va2  s  .  c  o m*/
 */
@Override
public void afterPropertiesSet() {
    DataSource dataSource = this.dataSource;
    if (dataSource == null) {
        throw new IllegalArgumentException("Property 'dataSource' is required");
    }
    if (this.validationQuery == null) {
        throw new IllegalArgumentException("Property 'validationQuery' is required");
    }

    try {
        boolean validated = false;
        long beginTime = System.currentTimeMillis();
        long deadLine = beginTime + this.timeout * 1000;
        SQLException latestEx = null;

        while (!validated && System.currentTimeMillis() < deadLine) {
            Connection con = null;
            Statement stmt = null;
            try {
                con = dataSource.getConnection();
                if (con == null) {
                    throw new CannotGetJdbcConnectionException("Failed to execute validation query: "
                            + "DataSource returned null from getConnection(): " + dataSource);
                }
                stmt = con.createStatement();
                stmt.execute(this.validationQuery);
                validated = true;
            } catch (SQLException ex) {
                latestEx = ex;
                logger.debug("Validation query [" + this.validationQuery + "] threw exception", ex);
                float rest = ((float) (deadLine - System.currentTimeMillis())) / 1000;
                if (rest > this.interval) {
                    logger.warn("Database has not started up yet - retrying in " + this.interval
                            + " seconds (timeout in " + rest + " seconds)");
                }
            } finally {
                JdbcUtils.closeStatement(stmt);
                JdbcUtils.closeConnection(con);
            }

            if (!validated) {
                Thread.sleep(this.interval * 1000);
            }
        }

        if (!validated) {
            throw new CannotGetJdbcConnectionException(
                    "Database has not started up within " + this.timeout + " seconds", latestEx);
        }

        float duration = (System.currentTimeMillis() - beginTime) / 1000;
        if (logger.isInfoEnabled()) {
            logger.info("Database startup detected after " + duration + " seconds");
        }
    } catch (InterruptedException ex) {
        // Re-interrupt current thread, to allow other threads to react.
        Thread.currentThread().interrupt();
    }
}

From source file:org.springframework.orm.hibernate3.SessionFactoryBuilderSupport.java

/**
 * Execute the given schema script on the given JDBC Connection.
 * <p>Note that the default implementation will log unsuccessful statements
 * and continue to execute. Override the <code>executeSchemaStatement</code>
 * method to treat failures differently.
 * @param con the JDBC Connection to execute the script on
 * @param sql the SQL statements to execute
 * @throws SQLException if thrown by JDBC methods
 * @see #executeSchemaStatement//from ww  w. j  a v  a  2s .co m
 */
protected void executeSchemaScript(Connection con, String... sql) throws SQLException {
    if (sql != null && sql.length > 0) {
        boolean oldAutoCommit = con.getAutoCommit();
        if (!oldAutoCommit) {
            con.setAutoCommit(true);
        }
        try {
            Statement stmt = con.createStatement();
            try {
                for (String sqlStmt : sql) {
                    executeSchemaStatement(stmt, sqlStmt);
                }
            } finally {
                JdbcUtils.closeStatement(stmt);
            }
        } finally {
            if (!oldAutoCommit) {
                con.setAutoCommit(false);
            }
        }
    }
}

From source file:ru.org.linux.site.User.java

public void block(Connection db, User by, String reason) throws SQLException {
    Statement st = null;/*from ww w .  j  a v a  2  s. c o  m*/
    PreparedStatement pst = null;

    try {
        st = db.createStatement();
        st.executeUpdate("UPDATE users SET blocked='t' WHERE id=" + id);

        pst = db.prepareStatement("INSERT INTO ban_info (userid, reason, ban_by) VALUES (?, ?, ?)");
        pst.setInt(1, id);
        pst.setString(2, reason);
        pst.setInt(3, by.getId());
        pst.executeUpdate();

        updateCache(db);
    } finally {
        JdbcUtils.closeStatement(st);
        JdbcUtils.closeStatement(pst);
    }
}

From source file:ru.org.linux.site.User.java

public void resetUnreadEvents(Connection db) throws SQLException {
    PreparedStatement st = db.prepareStatement("UPDATE users SET unread_events=0 where id=?");
    try {// www . j  a  v  a  2 s .c  om
        st.setInt(1, id);

        st.executeUpdate();
    } finally {
        JdbcUtils.closeStatement(st);
    }
}

From source file:ru.org.linux.spring.SearchQueueListener.java

public void handleMessage(SearchQueueSender.UpdateComments msgUpdate)
        throws SQLException, MessageNotFoundException, IOException, SolrServerException {
    logger.info("Indexing " + msgUpdate.getMsgids());

    Connection db = LorDataSource.getConnection();
    PreparedStatement pst = null;

    try {/*w w w.j  ava 2  s. c om*/
        pst = db.prepareStatement("SELECT message FROM msgbase WHERE id=?");

        for (Integer msgid : msgUpdate.getMsgids()) {
            Comment comment = new Comment(db, msgid);

            if (comment.isDeleted()) {
                logger.info("Deleting comment " + comment.getId() + " from solr");
                solrServer.deleteById(Integer.toString(comment.getId()));
            } else {
                //        ? ?? ?
                //  ? ??  -  , ..    ?
                //    
                Message topic = new Message(db, comment.getTopic());

                pst.setInt(1, comment.getId());
                ResultSet rs = pst.executeQuery();
                if (!rs.next()) {
                    throw new RuntimeException("Can't load message text for " + comment.getId());
                }

                String message = rs.getString(1);

                rs.close();

                solrServer.add(processComment(topic, comment, message));
            }
        }

        solrServer.commit();
    } finally {
        JdbcUtils.closeStatement(pst);
        JdbcUtils.closeConnection(db);
    }
}

From source file:ru.org.linux.spring.SearchQueueListener.java

private void reindexComments(Connection db, Message topic, CommentList comments)
        throws IOException, SolrServerException, SQLException {
    Collection<SolrInputDocument> docs = new ArrayList<SolrInputDocument>();
    List<String> delete = new ArrayList<String>();

    PreparedStatement pst = db.prepareStatement("SELECT message FROM msgbase WHERE id=?");

    try {//from  www. j  a  va2s  .co  m
        for (Comment comment : comments.getList()) {
            if (comment.isDeleted()) {
                delete.add(Integer.toString(comment.getId()));
            }

            pst.setInt(1, comment.getId());
            ResultSet rs = pst.executeQuery();
            if (!rs.next()) {
                throw new RuntimeException("Can't load message text for " + comment.getId());
            }

            String message = rs.getString(1);

            rs.close();

            docs.add(processComment(topic, comment, message));
        }
    } finally {
        JdbcUtils.closeStatement(pst);
    }

    if (!docs.isEmpty()) {
        solrServer.add(docs);
    }
    if (!delete.isEmpty()) {
        //logger.info("Deleting comments: "+delete);
        solrServer.deleteById(delete);
    }
}

From source file:uk.ac.cam.caret.sakai.rwiki.component.model.impl.SQLScriptMigration.java

/**
 * borrowed from LocalSessionFactoryBean in spring
 * //from  w  ww.  j  a v a 2s .c o m
 * @param con
 * @param sql
 * @throws SQLException
 */
protected void executeSchemaScript(Connection con, String[] sql, boolean newdb) throws SQLException {
    if (sql != null && sql.length > 0) {
        boolean oldAutoCommit = con.getAutoCommit();
        if (!oldAutoCommit) {
            con.setAutoCommit(true);
        }
        try {
            Statement stmt = con.createStatement(); // validated as closing
            try {
                for (int i = 0; i < sql.length; i++) {
                    if (sql[i].startsWith("message")) {
                        log.info("Data Migration " + sql[i]);
                    } else {
                        log.debug("Executing data migration statement: " + sql[i]);
                        try {
                            long start = System.currentTimeMillis();
                            int l = stmt.executeUpdate(sql[i]);
                            log.debug("   Done " + l + " rows in " + (System.currentTimeMillis() - start)
                                    + " ms");
                        } catch (SQLException ex) {
                            if (newdb) {
                                log.debug("Unsuccessful data migration statement: " + sql[i]);
                                log.debug("Cause: " + ex.getMessage());
                            } else {
                                log.warn("Unsuccessful data migration statement: " + sql[i]);
                                log.debug("Cause: " + ex.getMessage());
                            }
                        }
                    }
                }
            } finally {
                JdbcUtils.closeStatement(stmt);
            }
        } finally {
            if (!oldAutoCommit) {
                con.setAutoCommit(false);
            }
        }
    }
}