List of usage examples for org.apache.commons.dbutils DbUtils closeQuietly
public static void closeQuietly(Statement stmt)
Statement
, avoid closing if null and hide any SQLExceptions that occur. From source file:com.mirth.connect.server.migration.ServerMigrator.java
private void updateVersion(Version version) throws MigrationException { PreparedStatement statement = null; try {/*from w w w . ja v a2s . co m*/ if (getCurrentVersion() == null) { statement = getConnection().prepareStatement("INSERT INTO SCHEMA_INFO (VERSION) VALUES (?)"); } else { statement = getConnection().prepareStatement("UPDATE SCHEMA_INFO SET VERSION = ?"); } statement.setString(1, version.getSchemaVersion()); statement.executeUpdate(); } catch (SQLException e) { throw new MigrationException("Failed to update database version information.", e); } finally { DbUtils.closeQuietly(statement); } }
From source file:jp.co.golorp.emarf.sql.MetaData.java
/** * @param cn//from w w w . ja v a 2 s . c o m * ? * @param tableName * ?? * @return ???Set */ private static Set<String> getPrimaryKeys(final Connection cn, final String tableName) { List<String> pkList = null; ResultSet rs = null; try { // ?? DatabaseMetaData dmd = cn.getMetaData(); rs = dmd.getPrimaryKeys(null, null, tableName); while (rs.next()) { if (pkList == null) { pkList = new ArrayList<String>(); } String columnName = rs.getString("COLUMN_NAME"); // rdbms? 1,2,3, // sqlite?0,1,2, ?? int keySeq = rs.getShort("KEY_SEQ"); while (pkList.size() <= keySeq) { pkList.add(null); } pkList.set(keySeq, columnName); } } catch (SQLException e) { throw new SystemError(e); } finally { DbUtils.closeQuietly(rs); } List<String> primaryKeys = null; if (pkList != null) { for (String pk : pkList) { if (StringUtil.isNotBlank(pk)) { if (primaryKeys == null) { primaryKeys = new ArrayList<String>(); } primaryKeys.add(pk); } } } if (primaryKeys == null) { return null; } return new LinkedHashSet<String>(primaryKeys); }
From source file:io.seqware.pipeline.plugins.FileProvenanceQueryTool.java
private void bulkImportH2(StringBuilder tableCreateBuilder, Connection connection, Path importFile) throws SQLException { tableCreateBuilder.append("AS SELECT * FROM CSVREAD('").append(importFile.toString()) .append("', null, 'fieldSeparator=\t')"); Log.debug("Table creation query is: " + tableCreateBuilder.toString()); Statement createTableStatement = null; try {//from w ww. j a v a 2s . c o m createTableStatement = connection.createStatement(); createTableStatement.executeUpdate(tableCreateBuilder.toString()); } finally { DbUtils.closeQuietly(createTableStatement); } }
From source file:com.splicemachine.derby.utils.SpliceAdminIT.java
@Test public void testGetLoggers() throws Exception { CallableStatement cs = methodWatcher.prepareCall("call SYSCS_UTIL.SYSCS_GET_LOGGERS()"); ResultSet rs = cs.executeQuery(); TestUtils.FormattedResult fr = TestUtils.FormattedResult.ResultFactory .convert("call SYSCS_UTIL.SYSCS_GET_LOGGERS()", rs); System.out.println(fr.toString()); Assert.assertTrue(fr.size() >= 80); DbUtils.closeQuietly(rs); }
From source file:com.che.software.testato.domain.dao.jdbc.impl.IterationDAO.java
/** * Checks if an iteration is completed. In other words, checks if the * related comparison matrix has been prioritized. * //from www. j a va 2 s . c o m * @author Clement HELIOU (clement.heliou@che-software.com). * @param iterationId the given iteration id. * @return true if the iteration is ended, else false. * @since August, 2011. * @throws IterationSearchDAOException if an error occurs during the search. */ @Override public boolean isIterationCompleted(int iterationId) throws IterationSearchDAOException { LOGGER.debug("isIterationCompleted(" + iterationId + ")."); Connection connection = null; try { connection = getDataSource().getConnection(); return (Boolean) getQueryRunner().query(connection, "SELECT EXISTS( SELECT iteration_assignment_id FROM iteration_assignment WHERE analytical_prioritization_status = 'ENDED' AND iteration_assignment_id = ?) AS result ", new ScalarHandler("result"), new Object[] { iterationId }); } catch (SQLException e) { throw new IterationSearchDAOException(e); } finally { if (null != connection) { DbUtils.closeQuietly(connection); } } }
From source file:jp.mathes.databaseWiki.db.postgres.PostgresBackend.java
@SuppressWarnings({ "rawtypes", "unchecked" }) private PostgresDocument createEmptyDocument(final Connection conn, final String table, final String name, final String db) throws BackendException { Statement st = null;/*from w ww . j a va 2s. c o m*/ Statement st2 = null; ResultSet rs = null; ResultSet rs2 = null; PostgresDocument doc = new PostgresDocument(); doc.setTable(this.getSchemaName(table, db) + "." + this.getPlainTableName(table)); doc.setDatabase(db); doc.setName(name); try { String schema = this.getSchemaName(table, db); String plainTable = this.getPlainTableName(table); st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); StringBuilder sb = new StringBuilder(""); sb.append("select c.column_name, c.column_default, c.data_type, ccu.table_name, ccu.column_name"); sb.append(" from information_schema.columns c"); sb.append(" left join information_schema.key_column_usage kcu"); sb.append(" on kcu.table_schema = c.table_schema and kcu.table_name = c.table_name"); sb.append(" and kcu.column_name = c.column_name"); sb.append(" left join information_schema.table_constraints tc"); sb.append(" on tc.constraint_type='FOREIGN KEY' and tc.table_schema = c.table_schema"); sb.append(" and tc.table_name = c.table_name and tc.constraint_name = kcu.constraint_name"); sb.append(" left join information_schema.constraint_column_usage ccu"); sb.append( " on ccu.constraint_schema = tc.constraint_schema and ccu.constraint_name = tc.constraint_name"); sb.append(" where c.table_schema='%s' and c.table_name='%s'"); sb.append(" order by c.ordinal_position"); String queryString = String.format(sb.toString().replaceAll("[ ]+", " "), schema, plainTable); this.logString(queryString, "?"); rs = st.executeQuery(queryString); if (this.getNumRows(rs) == 0) { throw new BackendException(String.format("Table %s.%s has no columns which is not supported.", this.getSchemaName(table, db), this.getPlainTableName(table))); } String nameField = this.getNameField(conn, table, db); while (rs.next()) { String ctype = rs.getString(3); String cname = rs.getString(1); PostgresField field = null; if ("character varying".equals(ctype)) { field = new PostgresField<String>(); field.setType(FieldType.string); field.setValue(rs.getString(2)); } else if ("text".equals(ctype)) { field = new PostgresField<String>(); field.setType(FieldType.text); field.setValue(rs.getString(2)); } else if ("integer".equals(ctype) || "bigint".equals(ctype) || "smallint".equals(ctype) || "real".equals(ctype)) { field = new PostgresField<Integer>(); field.setType(FieldType.dec); field.setValue(rs.getInt(2)); } else if ("numeric".equals(ctype)) { field = new PostgresField<Double>(); field.setType(FieldType.num); field.setValue(rs.getDouble(2)); } else if ("date".equals(ctype)) { field = new PostgresField<Date>(); field.setType(FieldType.date); field.setValue(rs.getDate(2)); } if (field != null) { field.setName(cname); field.setUsage(FieldUsage.normal); if (nameField.equals(cname)) { field.setValue(name); } else if ("version".equals(cname)) { field.setUsage(FieldUsage.hidden); } String foreignTable = rs.getString(4); String foreignColumn = rs.getString(5); if (!StringUtils.isEmpty(foreignTable) && !StringUtils.isEmpty(foreignColumn)) { st2 = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); field.setUsage(FieldUsage.fixed); StringBuilder sb2 = new StringBuilder(); sb2.append("select distinct \"%s\" from \"%s\" order by \"%s\""); String queryString2 = String.format(sb2.toString().replaceAll("[ ]+", " "), foreignColumn, foreignTable, foreignColumn); this.logString(queryString2, "?"); rs2 = st2.executeQuery(queryString2); while (rs2.next()) { field.getAllowedValues().add(rs2.getObject(1)); } } doc.addField(cname, field); } } } catch (SQLException e) { throw new BackendException(e); } finally { DbUtils.closeQuietly(rs); DbUtils.closeQuietly(rs2); DbUtils.closeQuietly(st); DbUtils.closeQuietly(st2); } return doc; }
From source file:azkaban.scheduler.JdbcScheduleLoader.java
private Connection getConnection() throws ScheduleManagerException { Connection connection = null; try {/* ww w. java 2 s .c om*/ connection = super.getDBConnection(false); } catch (Exception e) { DbUtils.closeQuietly(connection); throw new ScheduleManagerException("Error getting DB connection.", e); } return connection; }
From source file:edu.pitt.dbmi.ipm.service.storage.PostgreStorage.java
@Override public void update(String statement) { Connection connection = null; PreparedStatement st = null;/*from w w w . ja v a2 s. c o m*/ try { connection = getConnection(); st = connection.prepareStatement(statement); st.executeUpdate(); st.close(); } catch (Exception ex) { // ex.printStackTrace(); if (ex.getMessage().indexOf("A result was returned when none was expected.") == -1) System.err.println("PostgreStatement update: " + ex.toString()); } finally { DbUtils.closeQuietly(st); DbUtils.closeQuietly(connection); } }
From source file:azkaban.project.JdbcProjectLoader.java
@Override public void uploadProjectFile(Project project, int version, String filetype, String filename, File localFile, String uploader) throws ProjectManagerException { logger.info("Uploading to " + project.getName() + " version:" + version + " file:" + filename); Connection connection = getConnection(); try {/*from ww w. j av a2 s . c om*/ uploadProjectFile(connection, project, version, filetype, filename, localFile, uploader); connection.commit(); logger.info("Commiting upload " + localFile.getName()); } catch (SQLException e) { logger.error(e); throw new ProjectManagerException("Error getting DB connection.", e); } finally { DbUtils.closeQuietly(connection); } }
From source file:de.iritgo.aktario.jdbc.JDBCManager.java
/** * Store data object changes to the database. * * @param object The data object to update. *///w w w .j a v a2 s . c o m private void update(DataObject object) { Connection connection = null; PreparedStatement stmt = null; try { connection = defaultDataSource.getConnection(); StringBuffer sqlAssigns = new StringBuffer("id=?"); for (Iterator i = object.getAttributes().entrySet().iterator(); i.hasNext();) { Map.Entry attribute = (Map.Entry) i.next(); if (attribute.getValue() instanceof IObjectList) { continue; } sqlAssigns.append(", " + (String) attribute.getKey() + "=?"); } String sql = "update " + object.getTypeId() + " set " + sqlAssigns.toString() + " where id=" + object.getUniqueId(); stmt = connection.prepareStatement(sql); putAttributesToStatement(object, stmt); stmt.execute(); Log.logVerbose("persist", "JDBCManager", "UPDATE " + object.getTypeId() + ":" + object.getUniqueId() + " |" + sql + "|"); } catch (Exception x) { // Log.logError ( // "persist", "JDBCManager", "Error while creating new database record: " + x); } finally { DbUtils.closeQuietly(stmt); DbUtils.closeQuietly(connection); } }