List of usage examples for org.springframework.jdbc.support JdbcUtils closeStatement
public static void closeStatement(@Nullable Statement stmt)
From source file:corner.migration.impl.DBMigrationInitializerTest.java
private void executeSQL(String... sql) { try {//from ww w. j a v a 2 s. c o m Connection con = this.factory.getSettings().getConnectionProvider().getConnection(); if (sql != null && sql.length > 0) { boolean oldAutoCommit = con.getAutoCommit(); if (!oldAutoCommit) { con.setAutoCommit(true); } try { Statement stmt = con.createStatement(); try { for (int i = 0; i < sql.length; i++) { executeSchemaStatement(stmt, sql[i]); } } finally { JdbcUtils.closeStatement(stmt); } } finally { if (!oldAutoCommit) { con.setAutoCommit(false); } } } } catch (SQLException e) { throw new RuntimeException(e); } }
From source file:com.enonic.cms.core.vacuum.VacuumServiceImpl.java
/** * Execute statement.// ww w . j a v a2s . c o m */ private void executeStatement(final Connection conn, final String sql) throws Exception { Statement stmt = null; try { stmt = conn.createStatement(); stmt.execute(sql); } finally { JdbcUtils.closeStatement(stmt); } }
From source file:com.scistor.queryrouter.server.impl.JdbcHandlerImpl.java
@Override public Map<String, String> queryForMeta(String tableName) { long begin = System.currentTimeMillis(); Map<String, String> result = Maps.newConcurrentMap(); Connection conn = null;/*w w w . j a v a 2s .c o m*/ PreparedStatement pst = null; try { conn = this.getJdbcTemplate().getDataSource().getConnection(); DatabaseMetaData dbMetaData = conn.getMetaData(); if (StringUtils.isNotEmpty(tableName)) { pst = conn.prepareStatement(String.format("select * from %s where 1=2", tableName)); ResultSetMetaData rsd = pst.executeQuery().getMetaData(); for (int i = 0; i < rsd.getColumnCount(); i++) { result.put(rsd.getColumnName(i + 1), rsd.getColumnTypeName(i + 1)); } } } catch (SQLException e1) { logger.error("queryId:{} select meta error:{}", 1, e1.getCause().getMessage()); } finally { JdbcUtils.closeConnection(conn); JdbcUtils.closeStatement(pst); logger.info("queryId:{} select meta cost:{} ms resultsize:{}", 1, System.currentTimeMillis() - begin, result.size()); } return result; }
From source file:net.firejack.platform.core.config.upgrader.SchemaUpgrader.java
/** * This method returns current package version by package lookup * * @param packageLookup/* w w w . j ava 2 s .c o m*/ * @return version */ private Version getDatabaseVersion(String packageLookup) { try { Connection connection = dataSource.getConnection(); try { connection.setAutoCommit(true); PreparedStatement statement = connection.prepareStatement("SELECT database_version " + "FROM opf_registry_node " + "WHERE lookup = '" + packageLookup + "'"); try { ResultSet resultSet = statement.executeQuery(); try { if (resultSet.next()) return new Version(resultSet.getInt(1)); else throw new BusinessFunctionException("Can't find database version number."); } finally { JdbcUtils.closeResultSet(resultSet); } } catch (SQLException e) { if (1054 == e.getErrorCode()) { return new Version(1); } throw new RuntimeException(e); } finally { JdbcUtils.closeStatement(statement); } } finally { connection.setAutoCommit(false); JdbcUtils.closeConnection(connection); } } catch (SQLException e) { throw new RuntimeException(e); } }
From source file:me.j360.idgen.impl.SequenceIdGenServiceImpl.java
/** * Gets the next id as a long. This method will only be called when * synchronized and when the data type is configured to be long. * /* www .j a v a 2s . co m*/ * @return the next id as a long. * @throws IdCreationException */ protected long getNextLongIdInner() { getLogger().debug("[IDGeneration Service] Requesting an Id using query: {}", query); try { // 2009.10.08 - without handling connection directly Connection conn = DataSourceUtils.getConnection(getDataSource()); PreparedStatement stmt = null; ResultSet rs = null; try { stmt = conn.prepareStatement(query); rs = stmt.executeQuery(); if (rs.next()) { return rs.getLong(1); } else { getLogger().error( "[IDGeneration Service] Unable to allocate a block of Ids. Query for Id did not return a value."); throw new IdCreationException( "[IDGeneration Service] Unable to allocate a block of Ids. Query for Id did not return a value."); } } finally { if (rs != null) { JdbcUtils.closeResultSet(rs); } if (stmt != null) { JdbcUtils.closeStatement(stmt); } // 2009.10.08 - without handling connection directly if (conn != null) { DataSourceUtils.releaseConnection(conn, getDataSource()); } } // 2009.10.08 - without handling connection directly } catch (Exception ex) { if (ex instanceof IdCreationException) throw (IdCreationException) ex; getLogger().error( "[IDGeneration Service] We can't get a connection. So, unable to allocate a block of Ids.", ex); throw new IdCreationException( "[IDGeneration Service] We can't get a connection. So, unable to allocate a block of Ids.", ex); } }
From source file:net.firejack.platform.core.config.upgrader.SchemaUpgrader.java
/** * This method update database package version and increase version number * * @param packageLookup - Openflame Package lookup * @param version - database version * @return version/*from w w w . j ava 2 s. c o m*/ */ private Version updateDatabaseVersion(String packageLookup, Version version) { try { Connection connection = dataSource.getConnection(); try { connection.setAutoCommit(true); Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); statement.addBatch("UPDATE opf_registry_node SET database_version = " + version.getToVersion() + " " + "WHERE lookup = '" + packageLookup + "';"); try { statement.executeBatch(); return new Version(version.getToVersion()); } finally { JdbcUtils.closeStatement(statement); } } finally { connection.setAutoCommit(false); JdbcUtils.closeConnection(connection); } } catch (SQLException e) { throw new RuntimeException(e); } }
From source file:com.enonic.cms.core.vacuum.VacuumServiceImpl.java
/** * gets array of primary keys that are to delete. read from database *//*from w w w . ja v a 2 s.co m*/ private List<Integer> readIdsFromDB(final Connection conn, final String select) throws SQLException { final List<Integer> ids = new ArrayList<Integer>(); Statement stmt = null; ResultSet rs = null; try { stmt = conn.createStatement(); rs = stmt.executeQuery(select); while (rs.next()) { ids.add(rs.getInt(1)); } } finally { JdbcUtils.closeResultSet(rs); JdbcUtils.closeStatement(stmt); } return ids; }
From source file:com.danidemi.jlubricant.springbatch.NamedJdbcCursorItemReader.java
/** * Close the cursor and database connection. */// ww w.j ava 2s . c o m @Override protected void cleanupOnClose() throws Exception { JdbcUtils.closeStatement(this.preparedStatement); }
From source file:corner.migration.services.impl.MigrationServiceImpl.java
/** * Execute the given schema script on the given JDBC Connection. * <p>/*from w w w . j a v a2 s . com*/ * 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 * @param con * the JDBC Connection to execute the script on * @param sql * the SQL statements to execute * @throws SQLException * if thrown by JDBC methods */ protected void executeSchemaScript(Connection con, String... sql) throws SQLException { if (sql != null && sql.length > 0) { boolean oldAutoCommit = con.getAutoCommit(); if (!oldAutoCommit) { con.setAutoCommit(false); } try { Statement stmt = con.createStatement(); try { for (int i = 0; i < sql.length; i++) { try { logger.info("[db-upgrade] " + sql[i]); executeSchemaStatement(stmt, sql[i]); } catch (SQLException se) { logger.error("[db-upgrade]" + se.toString(), se); throw se; } } } finally { JdbcUtils.closeStatement(stmt); } } finally { if (!oldAutoCommit) { con.setAutoCommit(false); } } } }
From source file:org.zenoss.zep.dao.impl.ElapsedTime.java
@Override public void optimizeTables() throws ZepException { final DatabaseType dbType = databaseCompatibility.getDatabaseType(); final String externalToolName = this.useExternalToolPath + "/pt-online-schema-change"; final String tableToOptimize = "event_summary"; // if we want to use percona's pt-online-schema-change to avoid locking the tables due to mysql optimize... //checks if external tool is available if (this.useExternalTool && dbType == DatabaseType.MYSQL && DaoUtils.executeCommand("ls " + externalToolName) == 0) { logger.info("Validating state of event_summary"); this.validateEventSummaryState(); logger.debug("Optimizing table: " + tableToOptimize + " via percona " + externalToolName); eventSummaryOptimizationTime.setStartTime(); String externalToolCommandPrefix = externalToolName + " --alter \"ENGINE=Innodb\" D=" + this.dbname + ",t="; String externalToolCommandSuffix = ""; if (System.getenv("USE_ZENDS") != null && Integer.parseInt(System.getenv("USE_ZENDS").trim()) == 1) { externalToolCommandSuffix = " --defaults-file=/opt/zends/etc/zends.cnf"; }//w w w .j a v a 2 s . c o m externalToolCommandSuffix += " " + this.externalToolOptions + " --alter-foreign-keys-method=drop_swap --host=" + this.hostname + " --port=" + this.port + " --user=" + this.username + " --password=" + this.password + " --execute"; int return_code = DaoUtils .executeCommand(externalToolCommandPrefix + tableToOptimize + externalToolCommandSuffix); if (return_code != 0) { logger.error("External tool failed on: " + tableToOptimize + ". Therefore, table:" + tableToOptimize + "will not be optimized."); } else { logger.debug( "Successfully optimized table: " + tableToOptimize + "using percona " + externalToolName); } eventSummaryOptimizationTime.setEndTime(); SendOptimizationTimeEvent(eventSummaryOptimizationTime, tableToOptimize, "percona"); if (this.tablesToOptimize.contains(tableToOptimize)) { this.tablesToOptimize.remove(tableToOptimize); } } else { if (this.useExternalTool) { logger.warn( "External tool not available. Table: " + tableToOptimize + " optimization may be slow."); } if (!this.tablesToOptimize.contains(tableToOptimize)) { this.tablesToOptimize.add(tableToOptimize); } } eventSummaryOptimizationTime.setStartTime(); // init so elapsedTime() == 0 try { logger.debug("Optimizing tables: {}", this.tablesToOptimize); this.template.execute(new ConnectionCallback<Object>() { @Override public Object doInConnection(Connection con) throws SQLException, DataAccessException { Boolean currentAutoCommit = null; Statement statement = null; try { currentAutoCommit = con.getAutoCommit(); con.setAutoCommit(true); statement = con.createStatement(); for (String tableToOptimize : tablesToOptimize) { logger.debug("Optimizing table: {}", tableToOptimize); final String sql; switch (dbType) { case MYSQL: sql = "OPTIMIZE TABLE " + tableToOptimize; break; case POSTGRESQL: sql = "VACUUM ANALYZE " + tableToOptimize; break; default: throw new IllegalStateException("Unsupported database type: " + dbType); } if (tableToOptimize == "event_summary") { eventSummaryOptimizationTime.setStartTime(); } statement.execute(sql); if (tableToOptimize == "event_summary") { eventSummaryOptimizationTime.setEndTime(); } logger.debug("Completed optimizing table: {}", tableToOptimize); } } finally { JdbcUtils.closeStatement(statement); if (currentAutoCommit != null) { con.setAutoCommit(currentAutoCommit); } } return null; } }); } finally { logger.info("Validating state of event_summary"); this.validateEventSummaryState(); } if (eventSummaryOptimizationTime.getElapsedTime() > 0) { SendOptimizationTimeEvent(eventSummaryOptimizationTime, "event_summary", ""); } logger.debug("Completed Optimizing tables: {}", tablesToOptimize); }