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.sql.SECExceptions.java

/**
 * Gets a count of errors where the description text matches. This is to
 * eliminate the repeat of entries from the application looping
 *
 * @param description String//from w w w .j  a v a 2 s  . co m
 * @return Integer count
 */
public static int getExistingException(String description) {
    int count = 0;
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
        conn = DBConnection.connectToDB();
        String sql = "SELECT COUNT(*) AS num FROM SECExceptions WHERE "
                + "timeOccurred >= CAST(CURRENT_TIMESTAMP AS DATE) AND exceptionDescrption LIKE ?";
        ps = conn.prepareStatement(sql);
        ps.setString(1, description + "%");

        rs = ps.executeQuery();
        while (rs.next()) {
            count = rs.getInt("num");
        }
    } catch (SQLException ex) {
        ExceptionHandler.Handle(ex);
    } finally {
        DbUtils.closeQuietly(conn);
        DbUtils.closeQuietly(ps);
        DbUtils.closeQuietly(rs);
    }
    return count;
}

From source file:com.gs.obevo.db.scenariotests.MigrationScenarioTest.java

private void validateInstance(String instanceName, String schemaName) throws Exception {
    DataSource ds = JdbcDataSourceFactory.createFromJdbcUrl(org.h2.Driver.class,
            H2JdbcDataSourceFactory.getUrl(instanceName, false), new Credential("sa", ""));
    JdbcHelper jdbc = new JdbcHelper();

    Connection conn = ds.getConnection();
    try {//from   www  .j  a  va 2 s  .  co  m
        int count = jdbc.queryForInt(conn, "select count(*) from " + schemaName + ".TABLE_A");
        assertEquals(6, count); // TODO verify the timestamp and ordering of rows in the table?
    } finally {
        DbUtils.closeQuietly(conn);
    }
}

From source file:com.gs.obevo.db.impl.platforms.AbstractSqlExecutor.java

@Override
public void executeWithinContext(PhysicalSchema schema, Procedure<Connection> runnable) {
    Connection conn = null;//  www .  j a  va2  s  . c o m
    try {
        conn = ds.getConnection();
        setDataSourceSchema(conn, schema);
        runnable.value(conn);
    } catch (Exception e) {
        throw new DeployerRuntimeException(e);
    } finally {
        DbUtils.closeQuietly(conn);
    }
}

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

public void importData(String filename) {
    Connection connection = null;
    PreparedStatement ps = null;//  w  w w  . jav a  2  s. c om
    try {
        connection = SpliceNetConnection.getConnection();
        ps = connection.prepareStatement(
                "call SYSCS_UTIL.IMPORT_DATA (?, ?, null,?,',',null,null,null,null,1,null,true,'utf-8')");
        ps.setString(1, schemaName);
        ps.setString(2, tableName);
        ps.setString(3, filename);
        try (ResultSet rs = ps.executeQuery()) {
            while (rs.next()) {

            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        DbUtils.closeQuietly(ps);
        DbUtils.commitAndCloseQuietly(connection);
    }
}

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

@Test
public void testEmbeddedMariaDB4j() throws Exception {
    DB db = DB.newEmbeddedDB(3308);/*from   www .  j  a v  a 2 s  .  com*/
    db.start();

    Connection conn = null;
    try {
        conn = db.getConnection();
        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");
        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:com.ouc.cpss.dao.BaseDao.java

/**
 * //from  www  .  ja v  a 2s.  c om
 *
 * @param sql
 * @param clazz
 * @return
 */
public List query(String sql, Class clazz) {
    List beans = null;
    Connection conn = null;
    try {
        conn = getConnection();
        QueryRunner qRunner = new QueryRunner();
        beans = (List) qRunner.query(conn, sql, new BeanListHandler(clazz));
        //BeanListHandler?ResultSet???List?
        //????ResultSet
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        DbUtils.closeQuietly(conn);
    }
    return beans;
}

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

@Override
public void releaseLock(String id, Connection connection) {
    try {//  w  w  w  . ja  va  2 s  . c om
        new QueryRunner().query(connection, String.format(RELEASE_LOCK_TEMPLATE, id),
                SingleResultSetHandlerFactory.<Long>newObjectHandler());
    } catch (Exception e) {
        LOG.error("Failed to call releaseLock on id {}.", id, e);
    }
    DbUtils.closeQuietly(connection);
}

From source file:com.gs.obevo.db.impl.platforms.hsql.HsqlDeployerTest.java

@Test
public void testDeploy() throws SQLException {
    DbEnvironment env = DbEnvironmentFactory.getInstance()
            .readOneFromSourcePath("./src/test/resources/platforms/hsql");
    DbDeployerAppContext context = env.buildAppContext("sa", "");

    context.setupEnvInfra();/*from www.  j  av a2  s. c  o m*/
    context.cleanEnvironment();
    context.deploy();
    // do a clean and deploy again to ensure that the clean functionality works
    context.cleanEnvironment();
    context.deploy();

    this.setup(context);
    // simple test to assert that the table has been created
    int result;
    Connection conn = context.getDataSource().getConnection();
    try {
        result = this.jdbc.queryForInt(conn, "select count(*) from SCHEMA1.TABLE_A");
        assertEquals(3, result);
        result = this.jdbc.queryForInt(conn, "select count(*) from SCHEMA1.VIEW1");
        assertEquals(3, result);
        // String columnListSql =
        // "select name from syscolumns where id in (select id from sysobjects where name = 'TEST_TABLE')";
        // List<String> columnsInTestTable = db2JdbcTemplate.query(columnListSql, new SingleColumnRowMapper<String>());
        // Assert.assertEquals(Lists.mutable.with("ID", "STRING", "MYNEWCOL"), FastList.newList(columnsInTestTable));
    } finally {
        DbUtils.closeQuietly(conn);
    }
}

From source file:com.gs.obevo.db.impl.platforms.mysql.MySqlDeployerIT.java

License:asdf

@Test
public void testDeploy() throws Exception {
    getAppContext.valueOf(1).setupEnvInfra().cleanEnvironment().deploy();

    // ensuring that we can modify
    DbDeployerAppContext dbDeployerAppContext = getAppContext.valueOf(2);
    dbDeployerAppContext.cleanEnvironment().setupEnvInfra().deploy();

    JdbcHelper jdbc = new JdbcHelper();

    Connection conn = ds.getConnection();
    try {/*from  w ww  .jav  a 2 s  .  c  om*/
        List<Map<String, Object>> results = jdbc.queryForList(conn,
                "select * from " + dbDeployerAppContext.getEnvironment().getPhysicalSchema("schema1")
                        + ".TABLE_A order by a_id");
        assertEquals(3, results.size());
        this.validateResults(results.get(0), 2, 3, "fasdfasd", "2013-02-02 11:11:11.65432", 9);
        this.validateResults(results.get(1), 3, 4, "ABC", null, 9);
        this.validateResults(results.get(2), 4, 2, "ABC", "2012-01-01 12:12:12", null);
    } finally {
        DbUtils.closeQuietly(conn);
    }
}

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

/**
 * Executes a query on the database and returns a CachedRowSet.
 * /*from   w  ww  .  j  a  v a2  s.c  o  m*/
 * @param expression
 *            the query expression to be executed.
 * @return the result of the query.
 * @throws SQLException
 */
public CachedRowSet executeCachedQuery(String expression) throws SQLException {
    Statement statement = null;

    try {
        statement = connection.createStatement();
        logger.debug("executing query:\n" + expression);
        ResultSet result = statement.executeQuery(expression);
        CachedRowSetImpl crs = new CachedRowSetImpl();
        crs.populate(result);
        DbUtils.closeQuietly(result);
        return crs;
    } catch (SQLException e) {
        throw e;
    } finally {
        DbUtils.closeQuietly(statement);
    }
}