Example usage for java.sql Statement getConnection

List of usage examples for java.sql Statement getConnection

Introduction

In this page you can find the example usage for java.sql Statement getConnection.

Prototype

Connection getConnection() throws SQLException;

Source Link

Document

Retrieves the Connection object that produced this Statement object.

Usage

From source file:org.apache.ddlutils.platform.ModelBasedResultSetIterator.java

/**
 * Closes the resources (connection, statement, resultset).
 *///  w ww .  j a va 2 s.c  o  m
public void cleanUp() {
    if (_cleanUpAfterFinish && (_resultSet != null)) {
        Connection conn = null;
        try {
            Statement stmt = _resultSet.getStatement();

            conn = stmt.getConnection();

            // also closes the resultset
            _platform.closeStatement(stmt);
        } catch (SQLException ex) {
            // we ignore it
        }
        _platform.returnConnection(conn);
        _resultSet = null;
    }
}

From source file:org.apache.ddlutils.platform.ModelBasedResultSetIterator.java

/**
 * Determines whether the connection is still open.
 * /*from www  .ja v  a 2  s.co m*/
 * @return <code>true</code> if the connection is still open
 */
public boolean isConnectionOpen() {
    if (_resultSet == null) {
        return false;
    }
    try {
        Statement stmt = _resultSet.getStatement();
        Connection conn = stmt.getConnection();

        return !conn.isClosed();
    } catch (SQLException ex) {
        return false;
    }
}

From source file:org.kuali.rice.test.ClearDatabaseLifecycle.java

protected void clearTables(final PlatformTransactionManager transactionManager, final DataSource dataSource) {
    Assert.assertNotNull("DataSource could not be located.", dataSource);
    try {//w  w w  . j ava2 s  . co  m
        StopWatch s = new StopWatch();
        s.start();
        new TransactionTemplate(transactionManager).execute(new TransactionCallback() {
            public Object doInTransaction(final TransactionStatus status) {
                verifyTestEnvironment(dataSource);
                return new JdbcTemplate(dataSource).execute(new StatementCallback() {
                    public Object doInStatement(Statement statement) throws SQLException {
                        String schemaName = statement.getConnection().getMetaData().getUserName().toUpperCase();
                        LOG.info("Clearing tables for schema " + schemaName);
                        if (StringUtils.isBlank(schemaName)) {
                            Assert.fail("Empty schema name given");
                        }
                        final List<String> reEnableConstraints = new ArrayList<String>();
                        DatabaseMetaData metaData = statement.getConnection().getMetaData();
                        Map<String, List<String[]>> exportedKeys = indexExportedKeys(metaData, schemaName);
                        final ResultSet resultSet = metaData.getTables(null, schemaName, null,
                                new String[] { "TABLE" });
                        final StringBuilder logStatements = new StringBuilder();
                        while (resultSet.next()) {
                            String tableName = resultSet.getString("TABLE_NAME");
                            if (shouldTableBeCleared(tableName)) {
                                if (!isUsingDerby(metaData) && isUsingOracle(metaData)) {
                                    List<String[]> exportedKeyNames = exportedKeys.get(tableName);
                                    if (exportedKeyNames != null) {
                                        for (String[] exportedKeyName : exportedKeyNames) {
                                            final String fkName = exportedKeyName[0];
                                            final String fkTableName = exportedKeyName[1];
                                            final String disableConstraint = "ALTER TABLE " + fkTableName
                                                    + " DISABLE CONSTRAINT " + fkName;
                                            logStatements.append("Disabling constraints using statement ->"
                                                    + disableConstraint + "<-\n");
                                            statement.addBatch(disableConstraint);
                                            reEnableConstraints.add("ALTER TABLE " + fkTableName
                                                    + " ENABLE CONSTRAINT " + fkName);
                                        }
                                    }
                                } else if (isUsingMySQL(metaData)) {
                                    statement.addBatch("SET FOREIGN_KEY_CHECKS = 0");
                                }
                                String deleteStatement = "DELETE FROM " + tableName;
                                logStatements.append(
                                        "Clearing contents using statement ->" + deleteStatement + "<-\n");
                                statement.addBatch(deleteStatement);
                            }
                        }
                        for (final String constraint : reEnableConstraints) {
                            logStatements
                                    .append("Enabling constraints using statement ->" + constraint + "<-\n");
                            statement.addBatch(constraint);
                        }
                        if (isUsingMySQL(metaData)) {
                            statement.addBatch("SET FOREIGN_KEY_CHECKS = 1");
                        }
                        LOG.info(logStatements);

                        int[] results = statement.executeBatch();
                        for (int index = 0; index < results.length; index++) {
                            if (results[index] == Statement.EXECUTE_FAILED) {
                                Assert.fail("Execution of database clear statement failed.");
                            }

                        }
                        resultSet.close();
                        LOG.info("Tables successfully cleared for schema " + schemaName);
                        return null;
                    }
                });
            }
        });
        s.stop();
        LOG.info("Time to clear tables: " + DurationFormatUtils.formatDurationHMS(s.getTime()));
    } catch (Exception e) {
        LOG.error(e);
        throw new RuntimeException(e);
    }
}

From source file:com.tera.common.database.query.CQueryService.java

@Override
public void closeStatement(Statement preparedStatement) {
    try {/*from   w w  w  .  ja va  2 s  . c  o  m*/
        if (preparedStatement.isClosed()) {
            // noinspection ThrowableInstanceNeverThrown
            log.error("Attempt to close PreparedStatement that is closed already", new Exception());
            return;
        }

        Connection connection = preparedStatement.getConnection();
        preparedStatement.close();
        connection.close();
    } catch (Exception e) {
        log.error("Error while closing PreparedStatement", e);
    }
}

From source file:org.openbravo.database.ConnectionProviderImpl.java

public void releaseStatement(Statement statement) throws SQLException {
    if (statement == null)
        return;/*from   w  w w .  j ava 2s  . c o m*/
    Connection conn = null;
    try {
        conn = statement.getConnection();
        statement.close();
        releaseConnection(conn);
    } catch (SQLException e) {
        log4j.error("releaseStatement: " + e);
        releaseConnection(conn);
        throw e;
    }
}

From source file:org.apache.hadoop.hive.ql.dataToDB.BaseDBExternalDataLoad.java

public void loadDataToDBTable(String delimiter) throws HiveException {
    if (config.isStructure()) {
        loadStructuredDataToDBTable();//from   w w  w.j av a  2s  . com
    } else if (config.isText()) {
        Statement stat = this.statement;
        try {
            if (newinsert && tolerent) {
                stat.getConnection().setAutoCommit(true);
            }
            loadTextDataToDBTable(stat, delimiter);
            if (newinsert && tolerent) {
                stat.getConnection().setAutoCommit(false);
            }
        } catch (HiveException e) {
            throw new HiveException(e.getMessage());
        } catch (SQLException e) {
            throw new HiveException(e.getMessage());
        }
    } else {
        throw new HiveException(ErrorMsg.INVALID_FILEFORMAT.getMsg());
    }
}

From source file:edu.harvard.i2b2.crc.dao.pdo.PdoQueryConceptDao.java

private void uploadTempTable(Statement tempStmt, String tempTable, List<String> patientNumList)
        throws SQLException {
    String createTempInputListTable = "create table " + tempTable + " ( char_param1 varchar(100) )";
    tempStmt.executeUpdate(createTempInputListTable);
    log.debug("created temp table" + tempTable);
    PreparedStatement preparedStmt = tempStmt.getConnection()
            .prepareStatement("insert into " + tempTable + " values (?)");
    // load to temp table
    // TempInputListInsert inputListInserter = new
    // TempInputListInsert(dataSource,TEMP_PDO_INPUTLIST_TABLE);
    // inputListInserter.setBatchSize(100);
    int i = 0;/*from  ww w  .ja  va 2 s .c  o  m*/
    for (String singleValue : patientNumList) {
        preparedStmt.setString(1, singleValue);
        preparedStmt.addBatch();
        log.debug("adding batch [" + i + "] " + singleValue);
        i++;
        if (i % 100 == 0) {
            log.debug("batch insert [" + i + "]");
            preparedStmt.executeBatch();

        }
    }
    log.debug("batch insert [" + i + "]");
    preparedStmt.executeBatch();
}

From source file:hnu.helper.DataBaseConnection.java

/**
 * This method closes a Connection-object and a Statement-object from
 * a Resulset-object.//from   ww  w  . ja  v  a 2 s.co m
 * IMPORTANT: Use this always after working on ResultSet returned by getRSfromStatement().
 */
public boolean closeResultSet(ResultSet rs) {
    boolean returnValue = true;

    Statement stmt = null;
    Connection conn = null;

    if (rs != null) {
        try {
            stmt = rs.getStatement();
        } catch (SQLException ex) {
            log.debug("Couldn't getStatement from rs.");
            returnValue = false;
        }
    }
    if (stmt != null) {
        try {
            conn = stmt.getConnection();
        } catch (SQLException ex) {
            log.debug("Couldn't getConnection from stmt.");
            returnValue = false;
        }
    }

    if (stmt != null) {
        try {
            stmt.close();
        } catch (SQLException ex) {
            log.debug("Couldn't close stmt.");
            returnValue = false;
        }
    }

    if (conn != null) {
        try {
            conn.close();
        } catch (SQLException ex) {
            log.debug("Couldn't close conn.");
            returnValue = false;
        }
    }

    return returnValue;
}

From source file:org.apache.ibatis.executor.resultset.FastResultSetHandler.java

protected ResultSet getNextResultSet(Statement stmt) throws SQLException {
    // Making this method tolerant of bad JDBC drivers
    try {//from w  w w . ja  v  a2  s. co  m
        if (stmt.getConnection().getMetaData().supportsMultipleResultSets()) {
            // Crazy Standard JDBC way of determining if there are more
            // results
            if (!((!stmt.getMoreResults()) && (stmt.getUpdateCount() == -1))) {
                return stmt.getResultSet();
            }
        }
    } catch (Exception e) {
        // Intentionally ignored.
    }
    return null;
}

From source file:com.toxind.benchmark.thrid.ibatis.sqlmap.engine.execution.SqlExecutor.java

private boolean moveToNextResultsSafely(StatementScope scope, Statement stmt) throws SQLException {
    if (forceMultipleResultSetSupport(scope)
            || stmt.getConnection().getMetaData().supportsMultipleResultSets()) {
        return stmt.getMoreResults();
    }/*from w w w . j  av  a 2 s. com*/
    return false;
}