Example usage for org.apache.commons.dbutils DbUtils closeQuietly

List of usage examples for org.apache.commons.dbutils DbUtils closeQuietly

Introduction

In this page you can find the example usage for org.apache.commons.dbutils DbUtils closeQuietly.

Prototype

public static void closeQuietly(Statement stmt) 

Source Link

Document

Close a Statement, avoid closing if null and hide any SQLExceptions that occur.

Usage

From source file:de.unibremen.informatik.tdki.combo.data.DBLayout.java

private boolean projectExists(String project) {
    CallableStatement callableStatement = null;
    boolean projectExists = false;
    try {/* w  w w  . j a v a 2 s  . c o m*/
        callableStatement = connection.prepareCall("CALL combo_project_exists('" + project + "',?)");
        callableStatement.registerOutParameter(1, java.sql.Types.INTEGER);
        callableStatement.executeUpdate();

        projectExists = (callableStatement.getInt(1) != 0);
    } catch (SQLException ex) {
        throw new RuntimeException(ex);
    } finally {
        DbUtils.closeQuietly(callableStatement);
    }
    return projectExists;
}

From source file:com.splicemachine.derby.test.framework.SpliceTableWatcher.java

public void start() {
    Statement statement = null;// w  ww. j av  a 2  s .  com
    ResultSet rs;
    Connection connection;
    synchronized (SpliceTableWatcher.class) {
        try {
            connection = (userName == null) ? SpliceNetConnection.getConnection()
                    : SpliceNetConnection.getConnectionAs(userName, password);
            rs = connection.getMetaData().getTables(null, schemaName, tableName, null);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    TableDAO tableDAO = new TableDAO(connection);

    try {
        if (rs.next()) {
            tableDAO.drop(schemaName, tableName);
        }
        connection.commit();
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }

    try {
        statement = connection.createStatement();
        statement.execute(String.format("create table %s.%s %s", schemaName, tableName, createString));
        connection.commit();
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        DbUtils.closeQuietly(rs);
        DbUtils.closeQuietly(statement);
        DbUtils.commitAndCloseQuietly(connection);
    }
}

From source file:hermes.store.SingleUserMessageStore.java

public Collection<Destination> getDestinationsFromDatabase() throws JMSException {
    final Connection connection = connectionPool.get();

    try {// ww  w .j  av  a2  s .  c o m
        return adapter.getDestinations(connection, getId());
    } catch (SQLException ex) {
        throw new HermesException(ex);
    } finally {
        if (connection != null) {
            DbUtils.closeQuietly(connection);
        }
    }
}

From source file:ccc.cli.NewDBQueries.java

/**
 * Update file store and lucene paths in the setting table.
 *
 * @param path The new path./* w ww .  ja v a 2  s.com*/
 */
public void updateSettingPaths(final String path) {
    PreparedStatement ps = null;

    try {
        // update file store path
        ps = _connection.prepareStatement("UPDATE settings SET value=? WHERE name = 'FILE_STORE_PATH'");
        ps.setString(1, path + "filestore");
        ps.executeUpdate();
        ps = _connection.prepareStatement("UPDATE settings SET value=? WHERE name = 'LUCENE_INDEX_PATH'");
        ps.setString(1, path + "lucene");
        ps.executeUpdate();
        _connection.commit();

    } catch (final SQLException e) {
        throw new RuntimeException(e);
    } finally {
        DbUtils.closeQuietly(ps);
    }
}

From source file:com.fyp.conflictanalysistestmav.controller.GraphController.java

public static ArrayList<Node> getGraphCategoryList(String disease) {

    ArrayList<Node> graphCategoryList = new ArrayList<>();
    try {//from w w  w .ja  v  a 2s . c  o  m
        connection = DBConnection.getDBConnection().getConnection();
        String SQL1 = "SELECT category_id, graph_category_id, category_name "
                + "FROM disease natural join graph " + "natural join graph_category natural join category "
                + "where disease_name = ? and " + "graph_id = disease_id and "
                + "graph_category.category_id = category.category_id;";

        preparedStatement = connection.prepareStatement(SQL1);
        preparedStatement.setString(1, disease);

        resultSet = preparedStatement.executeQuery();

        while (resultSet.next()) {
            Node node = new Node();
            node.setId(resultSet.getString("category_id"));
            node.setName(resultSet.getString("category_name"));
            node.setGraph_category_id(resultSet.getString("graph_category_id"));
            node.setType(NodeTypes.NODE_TYPE_CATEGORY);
            graphCategoryList.add(node);
        }

    } catch (SQLException | IOException | PropertyVetoException ex) {
        LOGGER.log(Level.SEVERE, ex.toString(), ex);
    } finally {
        try {
            DbUtils.closeQuietly(resultSet);
            DbUtils.closeQuietly(preparedStatement);
            DbUtils.close(connection);
        } catch (SQLException ex) {
            LOGGER.log(Level.SEVERE, ex.toString(), ex);
        }
    }

    return graphCategoryList;
}

From source file:com.mirth.connect.connectors.jdbc.DatabaseDispatcherQuery.java

@Override
public Response send(DatabaseDispatcherProperties connectorProperties, ConnectorMessage connectorMessage)
        throws DatabaseDispatcherException {
    long dispatcherId = connector.getDispatcherId();
    SimpleDataSource dataSource = dataSources.get(dispatcherId);

    if (dataSource == null) {
        dataSource = new SimpleDataSource();
        dataSources.put(dispatcherId, dataSource);
    }/*from w w w. j  av a 2 s.  com*/

    PreparedStatement statement = null;

    try {
        Connection connection = dataSource.getConnection(connectorProperties);
        statement = connection.prepareStatement(connectorProperties.getQuery());
        int i = 1;

        for (Object param : connectorProperties.getParameters()) {
            statement.setObject(i++, param);
        }

        /*
         * We do not use Statement.executeUpdate() here because it could prevent users from
         * executing a stored procedure. Executing a stored procedure in Postgres (and possibly
         * other databases) is done via SELECT myprocedure(), which breaks executeUpdate() since
         * it returns a result, even if the procedure itself returns void.
         */
        statement.execute();
        int numRows = statement.getUpdateCount();
        String responseData = null;
        String responseMessageStatus = null;

        if (numRows == -1) {
            responseMessageStatus = "Database write success";
        } else {
            responseMessageStatus = "Database write success, " + numRows + " rows updated";
        }

        return new Response(Status.SENT, responseData, responseMessageStatus);
    } catch (Exception e) {
        throw new DatabaseDispatcherException("Failed to write to database", e);
    } finally {
        DbUtils.closeQuietly(statement);
    }
}

From source file:com.pinterest.deployservice.db.DBDeployDAOImpl.java

@Override
public DeployQueryResultBean getAllDeploys(DeployQueryFilter filterBean) throws Exception {
    QueryRunner run = new QueryRunner(dataSource);
    ResultSetHandler<List<DeployBean>> h = new BeanListHandler<>(DeployBean.class);

    String queryStr;/*ww  w .j a v  a 2  s.  co  m*/
    if (StringUtils.isNotEmpty(filterBean.getFilter().getCommit())) {
        // TODO pretty hacky
        // It is very important to delete the commit from the filter, since we
        // want to return all deploys with commits later than this commit
        filterBean.getFilter().setCommit(null);
        filterBean.generateClauseAndValues();
        queryStr = String.format(GET_ALL_DEPLOYMENTS_WITH_COMMIT_TEMPLATE, filterBean.getWhereClause());
    } else {
        filterBean.generateClauseAndValues();
        queryStr = String.format(GET_ALL_DEPLOYMENTS_TEMPLATE, filterBean.getWhereClause());
    }

    Connection connection = dataSource.getConnection();
    try {
        List<DeployBean> deployBeans = run.query(connection, queryStr, h, filterBean.getValueArray());
        long total = run.query(connection, FOUND_ROWS, SingleResultSetHandlerFactory.newObjectHandler());
        long maxToReturn = filterBean.getFilter().getPageIndex() * filterBean.getFilter().getPageSize();
        return new DeployQueryResultBean(deployBeans, total, total > maxToReturn);
    } finally {
        DbUtils.closeQuietly(connection);
    }
}

From source file:com.che.software.testato.domain.dao.jdbc.impl.UserDAO.java

/**
 * Creates an user from his properties bean.
 * //from www  .  j av a2 s.c o  m
 * @author Clement HELIOU (clement.heliou@che-software.com).
 * @param userToCreateBean the properties to use to create the user.
 * @throws UserCreationDAOException if an error occurs during the creation.
 */
@Override
public void createUserFromBean(UserCreation userToCreateBean) throws UserCreationDAOException {
    LOGGER.debug("createUserFromBean(" + userToCreateBean.getLogin() + ").");
    Connection connection = null;
    try {
        connection = getDataSource().getConnection();
        connection.setAutoCommit(false);
        getQueryRunner().update(connection,
                "INSERT INTO \"user\"(user_id, \"login\", \"password\", \"name\", last_name, creation_date, job) VALUES(nextval('user_seq'), ?, md5(?), ?, ?, NOW(), ?) ",
                new Object[] { userToCreateBean.getLogin(), userToCreateBean.getPassword(),
                        userToCreateBean.getName().toUpperCase(), userToCreateBean.getLastName(),
                        userToCreateBean.getJob() });
        Integer createdUserID = (Integer) getQueryRunner().query(connection,
                "SELECT user_id::int FROM \"user\" WHERE \"login\" = ? ", new ScalarHandler("user_id"),
                new Object[] { userToCreateBean.getLogin() });
        getQueryRunner().update(connection, "INSERT INTO user_role(user_id, role) VALUES(?, 'ROLE_USER') ",
                new Object[] { createdUserID });
        if (userToCreateBean.isAdministrator()) {
            getQueryRunner().update(connection, "INSERT INTO user_role(user_id, role) VALUES(?, 'ROLE_ADMIN') ",
                    new Object[] { createdUserID });
        }
        if (userToCreateBean.isResponsable()) {
            getQueryRunner().update(connection, "INSERT INTO user_role(user_id, role) VALUES(?, 'ROLE_RESP') ",
                    new Object[] { createdUserID });
        }
        getQueryRunner().update(connection,
                "INSERT INTO user_service(user_id, service_id, hired_date) VALUES(?, ?, NOW()) ",
                new Object[] { createdUserID, userToCreateBean.getServiceId() });
        connection.commit();
    } catch (SQLException e) {
        try {
            connection.rollback();
        } catch (SQLException e1) {
            throw new UserCreationDAOException(e1);
        }
        throw new UserCreationDAOException(e);
    } finally {
        if (null != connection) {
            DbUtils.closeQuietly(connection);
        }
    }
}

From source file:net.big_oh.common.jdbc.JdbcProxyExerciser.java

private static void cleanOutTestTable(Connection con) throws SQLException {
    logger.info(StringUtils.center("clean out the test table", 100, "-"));

    Statement stmt = null;//from w  ww .j a  v a 2  s  . c  o m
    try {
        stmt = con.createStatement();
        stmt.executeUpdate("TRUNCATE TABLE TEST_TABLE");
    } finally {
        DbUtils.closeQuietly(stmt);
    }
}

From source file:com.mycompany.rubricatelefonica.DefaultUtenteDao.java

public UtenteModel getUtenteSmartphone(String email) {

    SmartphoneModel smartphoneModel = new SmartphoneModel();

    UtenteModel utenteModel = new UtenteModel();

    MysqlDataSource dataSource = new MysqlDataSource();

    dataSource.setUser("root");
    dataSource.setPassword("root");
    dataSource.setUrl("jdbc:mysql://localhost:3306/RubricaTelef");

    Connection conn = null;/*from w ww  .j a  va2s  .  c  om*/

    try {

        conn = dataSource.getConnection();

        PreparedStatement stmtUserInfo = conn.prepareStatement(USER_SMARTH_INFO);

        stmtUserInfo.setString(1, email);

        ResultSet rsUserInfoSet = stmtUserInfo.executeQuery();

        if (rsUserInfoSet.first()) {

            utenteModel.setNome(rsUserInfoSet.getString("nome"));
            utenteModel.setCognome(rsUserInfoSet.getString("cognome"));
            utenteModel.setEmail(rsUserInfoSet.getString("email"));
            smartphoneModel.setMarca(rsUserInfoSet.getString("marca"));
            smartphoneModel.setModello(rsUserInfoSet.getString("modello"));
            utenteModel.setSmartphone(smartphoneModel);
        }

    } catch (SQLException e) {
        System.out.println(e.getMessage());
        System.out.println("errore!! Connessione Fallita");
    } finally {

        DbUtils.closeQuietly(conn); //oppure try with resource
    }

    return utenteModel;

}