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.intelligentz.appointmentz.controllers.Data.java
public static String equipmentsGetRooms(String hospital_id) { String rooms = ""; try {/*from w w w . j ava 2s. co m*/ connection = DBConnection.getDBConnection().getConnection(); String SQL = "select * from room where hospital_id = ?"; preparedStatement = connection.prepareStatement(SQL); preparedStatement.setString(1, hospital_id); resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { String room_id = resultSet.getString("room_id"); String room_number = resultSet.getString("room_number"); rooms += "<tr><form action='./deleteRoom' method='post'><td>" + room_number + "</td><td>" + room_id + "</td><input type='hidden' name='room_id' value='" + room_id + "'><input type='hidden' name='hospital_id' value='" + hospital_id + "'>"; rooms += "<td><button type=\"submit\" onClick=\"return confirm('Do you wish to delete the Room. Ref: Room number = " + room_number + " Related devices will also be removed.');\" style='color:red'>delete</button></td>"; rooms += "</form></tr>"; } } catch (SQLException | IOException | PropertyVetoException e) { //throw new IllegalStateException rooms = "Error"; } finally { try { DbUtils.closeQuietly(resultSet); DbUtils.closeQuietly(preparedStatement); DbUtils.close(connection); } catch (SQLException ex) { Logger.getLogger(register.class.getName()).log(Level.SEVERE, ex.toString(), ex); } } return rooms; }
From source file:com.gs.obevo.db.impl.platforms.sybasease.SybaseAseDeployerMainIT.java
public static void validateStep2(DataSource ds, JdbcHelper jdbc) throws Exception { List<Map<String, Object>> results; Connection conn = ds.getConnection(); try {//from w ww .j a va 2 s . c om results = jdbc.queryForList(conn, "select * from TestTable order by idField"); } finally { DbUtils.closeQuietly(conn); } assertEquals(5, results.size()); validateResultRow(results.get(0), 1, "str1", 0); validateResultRow(results.get(1), 3, "str3Changed", 0); validateResultRow(results.get(2), 4, "str4", 0); validateResultRow(results.get(3), 5, "str5", 0); validateResultRow(results.get(4), 6, "str6", 0); }
From source file:com.che.software.testato.domain.dao.jdbc.impl.ServiceDAO.java
/** * Retrieves the id of the last user hired by a specific service. * //from w w w . j a v a 2 s . c om * @author Clement HELIOU (clement.heliou@che-software.com). * @param serviceId the service id. * @return the resulting user id. * @since July, 2011. * @throws ServiceSearchDAOException if an error occurs during the search. */ @Override public int getLastHiredUserIdFromServiceId(int serviceId) throws ServiceSearchDAOException { LOGGER.debug("getLastHiredUserIdFromServiceId(" + serviceId + ")."); Connection connection = null; try { connection = getDataSource().getConnection(); Object res = getQueryRunner().query(connection, "SELECT user_id::integer AS userId FROM user_service WHERE service_id = ? ORDER BY hired_date DESC ", new ScalarHandler("userId"), new Object[] { serviceId }); return (null != res) ? ((Integer) res) : -1; } catch (SQLException e) { throw new ServiceSearchDAOException(e); } finally { if (null != connection) { DbUtils.closeQuietly(connection); } } }
From source file:ccc.cli.Schema.java
private void create() { final DatabaseVendor vendor = DatabaseVendor.forConnectionString(_conString); final Connection newConnection = getConnection(vendor.driverClassName(), _conString, _username, getPassword());//from w w w . j a va 2 s .c o m LOG.info("Connected to " + _conString); int currentVersion = currentVersion(newConnection); LOG.info("Current database version: " + currentVersion); try { if (_drop) { doDrop(vendor, newConnection, currentVersion); currentVersion = NEW_DB_VERSION; } for (int i = (currentVersion + 1); i <= _version; i++) { doCreate(vendor, newConnection, i); // execute only when upgrading from 2 to 3. if (i == 3 && currentVersion < 3) { final StringToDecConverterUtil stdcu = new StringToDecConverterUtil(); stdcu.convertParagraphs(newConnection); } } commit(newConnection); } finally { DbUtils.closeQuietly(newConnection); } LOG.info("Finished."); }
From source file:de.iritgo.aktario.jdbc.Insert.java
/** * Perform the command./*from www .j ava2s .c o m*/ */ public void perform() { if (properties.get("table") == null) { Log.logError("persist", "Insert", "Missing table name"); return; } int size = 0; if (properties.get("size") != null) { size = ((Integer) properties.get("size")).intValue(); } JDBCManager jdbcManager = (JDBCManager) Engine.instance().getManager("persist.JDBCManager"); DataSource dataSource = jdbcManager.getDefaultDataSource(); Connection connection = null; PreparedStatement stmt = null; ArrayList columns = new ArrayList(8); ArrayList columnValues = new ArrayList(8); for (Iterator i = properties.entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry) i.next(); if (((String) entry.getKey()).indexOf("column.") == 0) { columns.add(((String) entry.getKey()).substring(7)); columnValues.add(entry.getValue()); } } int numColumns = columns.size(); StringBuffer sqlColumns = new StringBuffer("(id"); for (int i = 0; i < numColumns; ++i) { sqlColumns.append(", " + (String) columns.get(i)); } sqlColumns.append(")"); StringBuffer sqlValues = new StringBuffer("(?"); for (int i = 0; i < numColumns; ++i) { sqlValues.append(", ?"); } sqlValues.append(")"); String sql = "insert into " + properties.getProperty("table") + " " + sqlColumns.toString() + " values " + sqlValues.toString(); try { connection = dataSource.getConnection(); stmt = connection.prepareStatement(sql); if (size <= 0) { stmt.setLong(1, Engine.instance().getPersistentIDGenerator().createId()); for (int col = 0; col < numColumns; ++col) { stmt.setObject(col + 2, columnValues.get(col)); } stmt.execute(); } else { for (int row = 0; row < size; ++row) { stmt.setLong(1, Engine.instance().getPersistentIDGenerator().createId()); for (int col = 0; col < numColumns; ++col) { stmt.setObject(col + 2, ((Object[]) columnValues.get(col))[row]); } stmt.execute(); } } stmt.close(); Log.logVerbose("persist", "Insert", "INSERT |" + sql + "|"); } catch (SQLException x) { Log.logError("persist", "Insert", "Error while executing sql |" + sql + "|: " + x); } finally { DbUtils.closeQuietly(stmt); DbUtils.closeQuietly(connection); } }
From source file:com.che.software.testato.domain.dao.jdbc.impl.VersionDAO.java
/** * Retrieves the last version of a specific project. * // ww w . java 2 s. co m * @author Clement HELIOU (clement.heliou@che-software.com). * @param projectId the project id. * @return the resulting object id. * @since July, 2011. * @throws VersionSearchDAOException if an error occurs during the search. */ @Override public Version getLastVersionFromProjectId(int projectId) throws VersionSearchDAOException { LOGGER.debug("getLastVersionFromProjectId(" + projectId + ")."); Connection connection = null; try { connection = getDataSource().getConnection(); return getQueryRunner().query(connection, "SELECT version_id AS versionId, \"name\" FROM version WHERE project_id = ? AND version_id = (SELECT MAX(version_id) FROM version) ", new BeanHandler<Version>(Version.class), new Object[] { projectId }); } catch (SQLException e) { throw new VersionSearchDAOException(e); } finally { if (null != connection) { DbUtils.closeQuietly(connection); } } }
From source file:hermes.store.jdbc.MessageResultSetHandler.java
public void close() { log.debug("closing MessageResultSetHandler..."); DbUtils.closeQuietly(statement); DbUtils.closeQuietly(connection); connection = null; }
From source file:com.che.software.testato.domain.dao.jdbc.impl.MatrixResultDAO.java
/** * Creates the matrix results for a given iteration assignment. The related * matrix must be completed before calling this method. * /*from w w w. j a v a2s . c o m*/ * @author Clement HELIOU (clement.heliou@che-software.com). * @param iterationId the given iteration id. * @since August, 2011. * @throws MatrixResultCreationDAOException if an error occurs during the * creation. */ @Override public void createMatrixResults(int iterationId) throws MatrixResultCreationDAOException { LOGGER.debug("createMatrixResults(" + iterationId + ")."); Connection connection = null; try { connection = getDataSource().getConnection(); connection.setAutoCommit(false); for (MatrixResult result : getQueryRunner().query(connection, "SELECT first_script AS scriptId, iteration_assignment_id AS iterationAssignmentId, ((SUM((value/( SELECT SUM(value) FROM comparisonMatrixItem WHERE iteration_assignment_id = ? AND second_script = base.second_script GROUP BY second_script ORDER BY second_script ))))/COUNT(*))::numeric(15,2) AS percentage FROM comparisonMatrixItem base WHERE iteration_assignment_id = ? GROUP BY first_script,iteration_assignment_id ORDER BY first_script ", new BeanListHandler<MatrixResult>(MatrixResult.class), new Object[] { iterationId, iterationId })) { getQueryRunner().update(connection, "INSERT INTO iteration_assignment_source_script(script_id, iteration_assignment_id, percentage) VALUES(?, ?, ?) ", new Object[] { result.getScriptId(), result.getIterationAssignmentId(), result.getPercentage() }); } connection.commit(); } catch (SQLException e) { try { connection.rollback(); } catch (SQLException e1) { throw new MatrixResultCreationDAOException(e1); } throw new MatrixResultCreationDAOException(e); } finally { if (null != connection) { DbUtils.closeQuietly(connection); } } }
From source file:com.uiip.gviviani.esercizioweekend.interfaces.impl.DefaultPersonDAO.java
@Override public boolean inserisciPerson(PersonModel person, String nomeTel) { MysqlDataSource datasource = new MysqlDataSource(); datasource.setUser("root"); datasource.setPassword("root"); datasource.setUrl("jdbc:mysql://localhost:3306/Rubrica"); Connection connection = null; try {//from ww w.j av a 2 s. co m connection = datasource.getConnection(); String sql = "INSERT INTO contatti (nome, cognome, data_nascita, numero, modello) VALUE " + "(?, ?, ?, ?, ?);"; int id; String sql2 = "SELECT id FROM telefono WHERE name = ? ;"; PreparedStatement stat2 = connection.prepareStatement(sql2); stat2.setString(1, nomeTel); ResultSet res = stat2.executeQuery(); if (res.first()) { id = res.getInt("id"); PreparedStatement stat = connection.prepareStatement(sql); stat.setString(1, person.getNome()); stat.setString(2, person.getCognome()); stat.setString(3, person.getData()); stat.setString(4, person.getNumero()); stat.setInt(5, id); if (stat.executeUpdate() > 0) { return true; } } } catch (SQLException e) { logger.error(e); } finally { DbUtils.closeQuietly(connection); } return false; }
From source file:com.pinterest.deployservice.db.DatabaseUtil.java
public static void transactionalUpdate(BasicDataSource dataSource, List<UpdateStatement> updateStatements) throws Exception { QueryRunner queryRunner = new QueryRunner(); Connection connection = dataSource.getConnection(); boolean autoStatus = connection.getAutoCommit(); connection.setAutoCommit(false);//from w ww . j a v a 2s. c om try { for (UpdateStatement updateStatement : updateStatements) { queryRunner.update(connection, updateStatement.getStatement(), updateStatement.getValueArray()); } connection.commit(); } catch (SQLException e) { connection.rollback(); throw e; } finally { connection.setAutoCommit(autoStatus); DbUtils.closeQuietly(connection); } }