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:com.pinterest.deployservice.db.DBUtilDAOImpl.java

@Override
public Connection getLock(String id) {
    Connection connection = null;
    try {/*from   ww  w  .  ja v a2 s .c om*/
        connection = dataSource.getConnection();
        connection.setAutoCommit(false);
        long status = new QueryRunner().query(connection, String.format(GET_LOCK_TEMPLATE, id, LOCK_TIMEOUT),
                SingleResultSetHandlerFactory.<Long>newObjectHandler());
        if (status == 1L) {
            return connection;
        }
    } catch (Exception e) {
        LOG.error("Failed to call getLock on id {}.", id, e);
    }
    DbUtils.closeQuietly(connection);
    return null;
}

From source file:ccc.migration.DbUtilsDB.java

/**
 * Constructor./*from   w w  w . j av a  2 s.  c o  m*/
 *
 * @param ds JDBC datasource for the database.
 */
public DbUtilsDB(final DataSource ds) {
    require().notNull(ds);
    _ds = ds;
    try {
        _c = _ds.getConnection();
        Runtime.getRuntime().addShutdownHook(new Thread() {
            /** {@inheritDoc} */
            @SuppressWarnings("synthetic-access")
            @Override
            public void run() {
                DbUtils.closeQuietly(_c);
                log.info("Legacy connection closed.");
            }

        });
    } catch (final SQLException e) {
        throw new MigrationException(e);
    }
}

From source file:com.mirth.connect.server.util.DatabaseUtil.java

public static void executeScript(String script, boolean ignoreErrors) throws Exception {
    SqlSessionManager sqlSessionManger = SqlConfig.getSqlSessionManager();

    Connection conn = null;/* ww w.ja  v  a 2  s.c  om*/
    ResultSet resultSet = null;
    Statement statement = null;

    try {
        sqlSessionManger.startManagedSession();
        conn = sqlSessionManger.getConnection();

        /*
         * Set auto commit to false or an exception will be thrown when trying to rollback
         */
        conn.setAutoCommit(false);

        statement = conn.createStatement();

        Scanner s = new Scanner(script);

        while (s.hasNextLine()) {
            StringBuilder sb = new StringBuilder();
            boolean blankLine = false;

            while (s.hasNextLine() && !blankLine) {
                String temp = s.nextLine();

                if (temp.trim().length() > 0)
                    sb.append(temp + " ");
                else
                    blankLine = true;
            }

            // Trim ending semicolons so Oracle doesn't throw
            // "java.sql.SQLException: ORA-00911: invalid character"
            String statementString = StringUtils.removeEnd(sb.toString().trim(), ";");

            if (statementString.length() > 0) {
                try {
                    statement.execute(statementString);
                    conn.commit();
                } catch (SQLException se) {
                    if (!ignoreErrors) {
                        throw se;
                    } else {
                        logger.error("Error was encountered and ignored while executing statement: "
                                + statementString, se);
                        conn.rollback();
                    }
                }
            }
        }

    } catch (Exception e) {
        throw new Exception(e);
    } finally {
        DbUtils.closeQuietly(statement);
        DbUtils.closeQuietly(resultSet);
        DbUtils.closeQuietly(conn);
        sqlSessionManger.close();
    }
}

From source file:com.intelligentz.appointmentz.controllers.editBerry.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    try {//  w ww . j a va  2 s .co m
        String room_id = req.getParameter("room_id");
        //String room_number = req.getParameter("room_number");
        String auth = req.getParameter("auth_hidden");
        String serial = req.getParameter("serial_hidden");
        connection = DBConnection.getDBConnection().getConnection();
        String SQL1 = "update rpi set room_id = ? where serial= ?";
        preparedStmt = connection.prepareStatement(SQL1);
        preparedStmt.setString(1, room_id);
        preparedStmt.setString(2, serial);
        // execute the preparedstatement
        preparedStmt.execute();
        res.sendRedirect("./equipments?status=Successfully Updated Device Details Serial:" + serial
                + " -> Room_id:" + room_id);
    } catch (SQLException | PropertyVetoException ex) {
        LOGGER.log(Level.SEVERE, null, ex);
        res.sendRedirect("./error.jsp?error=Error in adding device!\n+" + ex.toString() + "");
    } finally {
        try {
            // DbUtils.closeQuietly(resultSet);
            DbUtils.closeQuietly(preparedStmt);
            DbUtils.close(connection);
        } catch (SQLException ex) {
            Logger.getLogger(register.class.getName()).log(Level.SEVERE, ex.toString(), ex);
        }
    }
}

From source file:com.uiip.gviviani.esercizioweekend.interfaces.impl.DefaultPersonDAO.java

@Override
public PersonModel getPersonInfo(String numero) {
    PersonModel personModel = new PersonModel();
    PhoneModel phone = new PhoneModel();
    MysqlDataSource datasource = new MysqlDataSource();
    datasource.setUser("root");
    datasource.setPassword("root");
    datasource.setUrl("jdbc:mysql://localhost:3306/Rubrica");
    Connection connection = null;
    try {//from  www .j  a va 2s.com
        connection = datasource.getConnection();
        String sql = "SELECT c.nome, c.cognome, c.data_nascita, t.name "
                + "FROM contatti c INNER JOIN telefono t ON (c.modello = t.id)" + "WHERE c.numero = ? ;";
        PreparedStatement stat = connection.prepareStatement(sql);
        stat.setString(1, numero);
        ResultSet res = stat.executeQuery();
        if (res.first()) {
            personModel.setNome(res.getString("nome"));
            personModel.setCognome(res.getString("cognome"));
            personModel.setData(res.getString("data_nascita"));
            personModel.setNumero(numero);
            phone.setNome(res.getString("name"));
            personModel.setModel(phone);
        } else {
            personModel = null;
        }
    } catch (SQLException e) {
        logger.error(e);
        personModel = null;
    } finally {
        DbUtils.closeQuietly(connection);
    }
    return personModel;
}

From source file:hermes.store.jdbc.JDBCConnectionPool.java

@Override
protected void closeObject(Connection connection) {
    DbUtils.closeQuietly(connection);
}

From source file:de.iritgo.aktario.jdbc.GetDatabaseVersion.java

/**
 * Perform the command./*  w ww  . j  av  a  2  s . c om*/
 *
 * @return The database name and version.
 */
public Object performWithResult() {
    JDBCManager jdbcManager = (JDBCManager) Engine.instance().getManager("persist.JDBCManager");
    DataSource dataSource = jdbcManager.getDefaultDataSource();

    Connection connection = null;

    try {
        if (version == null) {
            connection = dataSource.getConnection();

            DatabaseMetaData meta = connection.getMetaData();

            version = meta.getDatabaseProductName() + " " + meta.getDatabaseProductVersion();
        }

        return version;
    } catch (SQLException x) {
        Log.logError("persist", "Insert", "Unable to get database meta data: " + x);
    } finally {
        DbUtils.closeQuietly(connection);
    }

    return null;
}

From source file:ccc.cli.Users.java

/**
 * Create a user.// w  w w .j  a  v a 2s.  com
 *
 * @return The UUID of the new user.
 */
public UUID create() {
    final DatabaseVendor vendor = DatabaseVendor.forConnectionString(getConString());
    final Connection newConnection = getConnection(vendor.driverClassName(), getConString(), getUsername(),
            getPassword());
    try {
        final NewDBQueries queries = new NewDBQueries(newConnection);
        final UUID userId = queries.insertMigrationUser(getNewUsername(), getNewEmail(), getNewPassword());
        LOG.info("Created user: " + getNewUsername());
        return userId;
    } finally {
        DbUtils.closeQuietly(newConnection);
    }
}

From source file:com.spankr.tutorial.TestConnectionDAO.java

/**
 * @throws SQLException// w  ww  . j a  va 2 s .  c  om
 * 
 */
@Test
public void getSomeData() throws SQLException {
    Connection con = null;

    try {
        printActiveConnections();
        con = ds.getConnection();
        printActiveConnections();

        Statement stmt = null;
        log.info("Creating sample_table");
        stmt = con.createStatement();
        stmt.execute(
                "CREATE TABLE sample_table (id INT IDENTITY, first_name VARCHAR(30), last_name VARCHAR(30), age INT)");
        DbUtils.closeQuietly(stmt);

        PreparedStatement pstmt = null;
        log.info("Inserting a person into sample_table");
        pstmt = con.prepareStatement("INSERT INTO sample_table VALUES (null, ?, ?, ?)");
        pstmt.setString(1, "Bob");
        pstmt.setString(2, "Haskins");
        pstmt.setInt(3, 38);
        Assert.assertTrue(pstmt.executeUpdate() == 1); // success means exactly one row inserted
        DbUtils.closeQuietly(pstmt);

        log.info("Getting a count of rows in sample_table");
        stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT count(1) from sample_table");
        if (rs.next()) {
            long l = rs.getLong(1);
            assertTrue("Shouldn't get a zero count", l > 0);
            log.debug(String.format("Total records = %s", l));
        } else {
            fail("Nothing returned from the database query");
        }
    } catch (SQLException e) {
        fail("Unable to create the database table");
    } finally {
        DbUtils.closeQuietly(con);
        printActiveConnections();
    }
}

From source file:com.akman.excel.view.frmSelectImage.java

public void getImage() {
    try {/*from www .j  av  a2  s.  co  m*/
        Connection conn = null;
        conn = Javaconnect.ConnecrDb();

        String sql = "SELECT Image FROM ExcelData where Id = 1";

        pst = conn.prepareStatement(sql);

        rs = pst.executeQuery();

        if (rs.next()) {
            byte[] imagedata = rs.getBytes("Image");
            format = new ImageIcon(imagedata);
            Rectangle rect = lblImage.getBounds();
            //Scaling the image to fit in the picLabel
            Image scaledimage = format.getImage().getScaledInstance(rect.width, rect.height,
                    Image.SCALE_DEFAULT);
            //converting the image back to image icon to make an acceptable picLabel
            format = new ImageIcon(scaledimage);

            lblImage.setIcon(format);
        }

    } catch (SQLException ex) {
        Logger.getLogger(frmSelectImage.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        DbUtils.closeQuietly(rs);
        DbUtils.closeQuietly(pst);
        Connection conn = null;
        DbUtils.closeQuietly(conn);
    }
}