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.splicemachine.derby.utils.TimestampAdminIT.java

/**
 * Tests SYSCS_GET_TIMESTAMP_GENERATOR_INFO system procedure.
 *///w w  w.  ja va  2 s .  co m
@Test
public void testGetTimestampGeneratorInfo() throws Exception {
    String template = "call SYSCS_UTIL.SYSCS_GET_TIMESTAMP_GENERATOR_INFO()";
    CallableStatement cs = methodWatcher.prepareCall(template);
    ResultSet rs = cs.executeQuery();
    int rowCount = 0;
    while (rs.next()) {
        rowCount++;
        long num = rs.getLong(1);
        Assert.assertTrue("Unexpected number of timestamps", num > 0);
    }
    Assert.assertTrue(rowCount == 1);
    DbUtils.closeQuietly(rs);
}

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

@Override
public void starting(Description description) {
    LOG.trace("Starting");
    Connection connection = null;
    Statement statement = null;//from   w ww .  j a  v a 2 s.c o  m
    ResultSet rs = null;
    try {
        connection = userName == null ? SpliceNetConnection.getConnection()
                : SpliceNetConnection.getConnectionAs(userName, password);
        rs = connection.getMetaData().getTables(null, schemaName, viewName, null);
        if (rs.next()) {
            executeDrop(schemaName, viewName);
        }
        connection.commit();
        statement = connection.createStatement();
        statement.execute(CREATE_VIEW + schemaName + "." + viewName + " " + createString);
        connection.commit();
    } catch (Exception e) {
        LOG.error("Create view statement is invalid ");
        e.printStackTrace(System.err);
        throw new RuntimeException(e);
    } finally {
        DbUtils.closeQuietly(rs);
        DbUtils.closeQuietly(statement);
        DbUtils.commitAndCloseQuietly(connection);
    }
    super.starting(description);
}

From source file:ca.qc.adinfo.rouge.social.db.SocialDb.java

public static Collection<Long> getFriends(DBManager dbManager, long userId) {

    Collection<Long> friends = new ArrayList<Long>();

    Connection connection = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;/*from   w ww  . j a  v a  2s.  co  m*/

    String sql = "SELECT `friend_user_id` FROM rouge_social_friends WHERE `user_id` = ? ";

    try {
        connection = dbManager.getConnection();
        stmt = connection.prepareStatement(sql);
        stmt.setLong(1, userId);

        rs = stmt.executeQuery();

        while (rs.next()) {
            friends.add(rs.getLong("friend_user_id"));
        }

        return friends;

    } catch (SQLException e) {
        log.error(stmt);
        log.error(e);
        return null;

    } finally {

        DbUtils.closeQuietly(rs);
        DbUtils.closeQuietly(stmt);
        DbUtils.closeQuietly(connection);
    }
}

From source file:com.akman.excel.controller.CURDInvoice.java

public static void Delete() {

    Connection conn = Javaconnect.ConnecrDb();
    PreparedStatement pst = null;
    ResultSet rs = null;/*from w  w  w . j  a v a  2 s  . c om*/
    try {

        String sql1 = "DELETE  FROM Invoice";
        pst = conn.prepareStatement(sql1);
        pst.execute();

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

From source file:ch.vorburger.mariadb4j.tests.MariaDB4jSampleTutorialTest.java

@Test
public void testEmbeddedMariaDB4j() throws Exception {
    DBConfigurationBuilder config = DBConfigurationBuilder.newBuilder();
    config.setPort(0); // 0 => autom. detect free port
    DB db = DB.newEmbeddedDB(config.build());
    db.start();//from w w  w  . j a v a2s .c o m

    String dbName = "mariaDB4jTest"; // or just "test"
    if (!dbName.equals("test")) {
        // mysqld out-of-the-box already has a DB named "test"
        // in case we need another DB, here's how to create it first
        db.createDB(dbName);
    }

    Connection conn = null;
    try {
        conn = DriverManager.getConnection(config.getURL(dbName), "root", "");
        QueryRunner qr = new QueryRunner();

        // Should be able to create a new table
        qr.update(conn, "CREATE TABLE hello(world VARCHAR(100))");

        // Should be able to insert into a table
        qr.update(conn, "INSERT INTO hello VALUES ('Hello, world')");

        // Should be able to select from a table
        List<String> results = qr.query(conn, "SELECT * FROM hello", new ColumnListHandler<String>());
        Assert.assertEquals(1, results.size());
        Assert.assertEquals("Hello, world", results.get(0));

        // Should be able to source a SQL file
        db.source("ch/vorburger/mariadb4j/testSourceFile.sql", "root", null, dbName);
        results = qr.query(conn, "SELECT * FROM hello", new ColumnListHandler<String>());
        Assert.assertEquals(3, results.size());
        Assert.assertEquals("Hello, world", results.get(0));
        Assert.assertEquals("Bonjour, monde", results.get(1));
        Assert.assertEquals("Hola, mundo", results.get(2));
    } finally {
        DbUtils.closeQuietly(conn);
    }
}

From source file:ca.qc.adinfo.rouge.leaderboard.db.LeaderboardDb.java

public static Leaderboard getLeaderboard(DBManager dbManager, String key) {

    Connection connection = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;/*from  w  ww  . j a va  2  s  .  com*/

    String sql = "SELECT score, user_id FROM rouge_leaderboard_score "
            + "WHERE `leaderboard_key` = ? ORDER BY `score` DESC LIMIT 5;";

    try {
        connection = dbManager.getConnection();
        stmt = connection.prepareStatement(sql);

        stmt.setString(1, key);

        Leaderboard leaderboard = new Leaderboard(key);

        rs = stmt.executeQuery();

        while (rs.next()) {
            Score score = new Score(rs.getLong("user_id"), rs.getLong("score"));
            leaderboard.addScore(score);
        }

        return leaderboard;

    } catch (SQLException e) {
        log.error(stmt);
        log.error(e);
        return null;

    } finally {

        DbUtils.closeQuietly(rs);
        DbUtils.closeQuietly(stmt);
        DbUtils.closeQuietly(connection);
    }
}

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

@Override
public boolean aggiornaPersonInfo(String numero, String data) {
    MysqlDataSource datasource = new MysqlDataSource();
    datasource.setUser("root");
    datasource.setPassword("root");
    datasource.setUrl("jdbc:mysql://localhost:3306/Rubrica");
    Connection connection = null;
    try {// www .  ja  va 2s  .  c om
        connection = datasource.getConnection();
        String sql = "UPDATE contatti SET data_nascita = ?" + "WHERE numero = ? ;";
        PreparedStatement stat = connection.prepareStatement(sql);
        stat.setString(1, data);
        stat.setString(2, numero);
        if (stat.executeUpdate() > 0) {
            return true;
        }
    } catch (SQLException e) {
        logger.error(e);
    } finally {
        DbUtils.closeQuietly(connection);
    }
    return false;
}

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

/**
 * Intention search from a bean of criterions.
 * /*w  ww . j  a  va 2  s  . co m*/
 * @author Clement HELIOU (clement.heliou@che-software.com).
 * @param searchBean the criterions to use for the search.
 * @return the resulting object list.
 * @since July, 2011.
 * @throws IntentionSearchDAOException if an error occurs during the search.
 */
@Override
public List<Intention> searchIntention(IntentionSearch searchBean) throws IntentionSearchDAOException {
    LOGGER.debug("searchIntention().");
    Connection connection = null;
    try {
        connection = getDataSource().getConnection();
        List<Object> params = new ArrayList<Object>();
        return getQueryRunner().query(connection, getIntentionSearchQueryFromCriterion(searchBean, params),
                new BeanListHandler<Intention>(Intention.class), params.toArray());
    } catch (SQLException e) {
        throw new IntentionSearchDAOException(e);
    } finally {
        if (null != connection) {
            DbUtils.closeQuietly(connection);
        }
    }
}

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

/**
 * Perform the command./*from ww  w . ja v a2 s . com*/
 */
public void perform() {
    if (properties.get("id") == null) {
        Log.logError("persist", "DeleteUser", "Missing unique id for the user to delete");

        return;
    }

    UserRegistry userRegistry = Server.instance().getUserRegistry();
    long userId = ((Long) properties.get("id")).longValue();
    User user = userRegistry.getUser(userId);

    if (user == null) {
        Log.logError("persist", "DeleteUser", "Unable to find user with id " + userId);

        return;
    }

    JDBCManager jdbcManager = (JDBCManager) Engine.instance().getManager("persist.JDBCManager");
    DataSource dataSource = jdbcManager.getDefaultDataSource();

    Connection connection = null;
    PreparedStatement stmt = null;

    try {
        connection = dataSource.getConnection();

        stmt = connection.prepareStatement("delete from IritgoUser where id=?");
        stmt.setLong(1, userId);
        stmt.execute();
        stmt.close();

        stmt = connection.prepareStatement("delete from IritgoNamedObjects where userId=?");
        stmt.setLong(1, userId);
        stmt.execute();
        stmt.close();

        Log.logVerbose("persist", "DeleteUser", "DELETE USER " + userId);
    } catch (SQLException x) {
        Log.logError("persist", "DeleteUser", "Error while storing user with id " + userId + ": " + x);
    } finally {
        DbUtils.closeQuietly(stmt);
        DbUtils.closeQuietly(connection);
    }
}

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

/**
 * Transition search from a bean of criterions.
 * /*  w ww .  j av a 2  s .c o  m*/
 * @author Clement HELIOU (clement.heliou@che-software.com).
 * @param searchBean the criterions to use for the search.
 * @return the resulting object list.
 * @since July, 2011.
 * @throws TransitionSearchDAOException if an error occurs during the
 *         search.
 */
@Override
public List<Transition> searchTransition(TransitionSearch searchBean) throws TransitionSearchDAOException {
    LOGGER.debug("searchTransition().");
    Connection connection = null;
    try {
        connection = getDataSource().getConnection();
        List<Object> params = new ArrayList<Object>();
        return getQueryRunner().query(connection, getTransitionSearchQueryFromCriterion(searchBean, params),
                new BeanListHandler<Transition>(Transition.class), params.toArray());
    } catch (SQLException e) {
        throw new TransitionSearchDAOException(e);
    } finally {
        if (null != connection) {
            DbUtils.closeQuietly(connection);
        }
    }
}