Java 类org.springframework.jdbc.datasource.DataSourceUtils 实例源码

项目:EasyTransaction    文件:DefaultTransStatusLoggerImpl.java   
@Override
public void writeExecuteFlag(String appId, String busCode, String trxId, String pAppId, String pBusCode, String pTrxId, int status) {

    Connection connection = DataSourceUtils.getConnection(selctor.selectDataSource(appId, busCode, trxId));

    try {
        PreparedStatement prepareStatement = connection.prepareStatement("INSERT INTO `executed_trans` (`app_id`, `bus_code`, `trx_id`,`p_app_id`, `p_bus_code`, `p_trx_id`,`status`) VALUES ( ?, ?, ?, ?, ?, ?, ?);");
        prepareStatement.setString(1, appId);
        prepareStatement.setString(2, busCode);
        prepareStatement.setString(3, trxId);
        prepareStatement.setString(4, pAppId);
        prepareStatement.setString(5, pBusCode);
        prepareStatement.setString(6, pTrxId);
        prepareStatement.setInt(7, status);

        int executeUpdate = prepareStatement.executeUpdate();
        if(executeUpdate != 1){
            throw new RuntimeException(String.format("insert count(%s) Error!%s %s %s %s %s %s %s", executeUpdate,appId,busCode,trxId,pAppId,pBusCode,pTrxId,status));
        }
    } catch (SQLException e) {
        throw new RuntimeException("insert Sql failed,check whether the same transaction has been executed?",e);
    }
}
项目:EasyTransaction    文件:DefaultTransStatusLoggerImpl.java   
@Override
public void updateExecuteFlagForSlaveTrx(TransactionId pId, EasyTransRequest<?, ?> request, int status) {

    BusinessIdentifer businessIdentifer = request.getClass().getAnnotation(BusinessIdentifer.class);

    Connection connection = DataSourceUtils.getConnection(selctor.selectDataSource(businessIdentifer.appId(),businessIdentifer.busCode(),request));

    try {
        PreparedStatement prepareStatement = connection.prepareStatement("UPDATE `executed_trans` SET `status` =  ? WHERE  `p_app_id` =  ? AND `p_bus_code` =  ? AND `p_trx_id` = ?;");
        prepareStatement.setInt(1, status);
        prepareStatement.setString(2, pId.getAppId());
        prepareStatement.setString(3, pId.getBusCode());
        prepareStatement.setString(4, pId.getTrxId());
        prepareStatement.executeUpdate();
    } catch (SQLException e) {
        throw new RuntimeException("updateExecuteFlagForSlaveTrx failed ",e);
    }
}
项目:DynamicDataSource    文件:DynamicMysqlDataSource.java   
/**
 * 自动上线可用数据源<br/>
 * 检查AbnormalSlaves,如果正常则丢回normalSlaves 
 */
protected void checkAbnormalSlaves(){
    //循环检查所有的失效从库数据源
    for(int i = 0; i < abnormalSlaves.size();i++){ 
        DataSource ds = null;
        Connection conn = null;
        try {
            ds = abnormalSlaves.get(i);
            //step检测可连接性
            String ipAndPort = getMapKey(ds);
            if(ConnUtil.isReachable(ipAndPort, validationQueryTimeout)){
                //step:  数据库直连检测
                conn = ds.getConnection(); 
                validateSlaveStatus(conn);
                online(ds);
            }
            break;
        } catch (Throwable e) { 
            continue;
        }finally{
            if(conn != null && ds != null) DataSourceUtils.releaseConnection(conn, ds);
        } 
    }
}
项目:DynamicDataSource    文件:DynamicMysqlDataSource.java   
/**
 * 自动下线无效数据源<br/>
 * 检查snormalSlaves,如果不正常则丢到AbnormalSlave
 */
protected void checkNormalSlaves(){
    //循环检查所有的失效从库数据源
    for(int i = 0; i < normalSlaves.size();i++){
        DataSource ds = null;
        Connection conn = null;
        try {
            ds = normalSlaves.get(i);
            //step检测可连接性
            String ipAndPort = getMapKey(ds);
            if(!ConnUtil.isReachable(ipAndPort, validationQueryTimeout)){
                throw new Exception("不能连接到"+ipAndPort);
            }
            conn = ds.getConnection();
            validateSlaveStatus(conn);
        } catch (Throwable e) {
            logger.error("数据源检查线程发现不可用的数据源",e);
            offline(ds,e.getMessage());
            break;
        }finally{
            if(conn != null && ds != null) DataSourceUtils.releaseConnection(conn, ds);
        } 
    }
}
项目:lams    文件:DatabasePopulatorUtils.java   
/**
 * Execute the given {@link DatabasePopulator} against the given {@link DataSource}.
 * @param populator the {@code DatabasePopulator} to execute
 * @param dataSource the {@code DataSource} to execute against
 * @throws DataAccessException if an error occurs, specifically a {@link ScriptException}
 */
public static void execute(DatabasePopulator populator, DataSource dataSource) throws DataAccessException {
    Assert.notNull(populator, "DatabasePopulator must be provided");
    Assert.notNull(dataSource, "DataSource must be provided");
    try {
        Connection connection = DataSourceUtils.getConnection(dataSource);
        try {
            populator.populate(connection);
        }
        finally {
            if (connection != null) {
                DataSourceUtils.releaseConnection(connection, dataSource);
            }
        }
    }
    catch (Exception ex) {
        if (ex instanceof ScriptException) {
            throw (ScriptException) ex;
        }

        throw new UncategorizedScriptException("Failed to execute database script", ex);
    }
}
项目:lams    文件:AbstractSequenceMaxValueIncrementer.java   
/**
 * Executes the SQL as specified by {@link #getSequenceQuery()}.
 */
@Override
protected long getNextKey() throws DataAccessException {
    Connection con = DataSourceUtils.getConnection(getDataSource());
    Statement stmt = null;
    ResultSet rs = null;
    try {
        stmt = con.createStatement();
        DataSourceUtils.applyTransactionTimeout(stmt, getDataSource());
        rs = stmt.executeQuery(getSequenceQuery());
        if (rs.next()) {
            return rs.getLong(1);
        }
        else {
            throw new DataAccessResourceFailureException("Sequence query did not return a result");
        }
    }
    catch (SQLException ex) {
        throw new DataAccessResourceFailureException("Could not obtain sequence value", ex);
    }
    finally {
        JdbcUtils.closeResultSet(rs);
        JdbcUtils.closeStatement(stmt);
        DataSourceUtils.releaseConnection(con, getDataSource());
    }
}
项目:lams    文件:NativeJdbcExtractorAdapter.java   
/**
 * Check for a ConnectionProxy chain, then delegate to doGetNativeConnection.
 * <p>ConnectionProxy is used by Spring's TransactionAwareDataSourceProxy
 * and LazyConnectionDataSourceProxy. The target connection behind it is
 * typically one from a local connection pool, to be unwrapped by the
 * doGetNativeConnection implementation of a concrete subclass.
 * @see #doGetNativeConnection
 * @see org.springframework.jdbc.datasource.ConnectionProxy
 * @see org.springframework.jdbc.datasource.DataSourceUtils#getTargetConnection
 * @see org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy
 * @see org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy
 */
@Override
public Connection getNativeConnection(Connection con) throws SQLException {
    if (con == null) {
        return null;
    }
    Connection targetCon = DataSourceUtils.getTargetConnection(con);
    Connection nativeCon = doGetNativeConnection(targetCon);
    if (nativeCon == targetCon) {
        // We haven't received a different Connection, so we'll assume that there's
        // some additional proxying going on. Let's check whether we get something
        // different back from the DatabaseMetaData.getConnection() call.
        DatabaseMetaData metaData = targetCon.getMetaData();
        // The following check is only really there for mock Connections
        // which might not carry a DatabaseMetaData instance.
        if (metaData != null) {
            Connection metaCon = metaData.getConnection();
            if (metaCon != null && metaCon != targetCon) {
                // We've received a different Connection there:
                // Let's retry the native extraction process with it.
                nativeCon = doGetNativeConnection(metaCon);
            }
        }
    }
    return nativeCon;
}
项目:bdf2    文件:DbCommonServiceImpl.java   
public List<String> findDefaultColumnType(String dbInfoId) throws Exception {
    DataSource ds = this.getDataSourceByDbInfoId(dbInfoId);
    Connection conn = null;
    ResultSet resultSet = null;
    try {
        conn = DataSourceUtils.getConnection(ds);
        DatabaseMetaData metaData = conn.getMetaData();
        resultSet = metaData.getTypeInfo();
        List<String> list = new ArrayList<String>();
        while (resultSet.next()) {
            String typeName = resultSet.getString("TYPE_NAME").toUpperCase();
            list.add(typeName);
        }
        return list;
    } finally {
        JdbcUtils.closeResultSet(resultSet);
        JdbcUtils.closeConnection(conn);
    }
}
项目:bdf2    文件:EntityPR.java   
private List<String> loadTablePrimaryKeys(String tableName)throws Exception{
    DataSource ds=this.getJdbcTemplate().getDataSource();
    Connection con = DataSourceUtils.getConnection(ds);
    List<String> primaryKeyList=new ArrayList<String>();
    Statement stmt = null;
    ResultSet rs=null;
    try{
        DatabaseMetaData metaData = con.getMetaData();
        rs = metaData.getPrimaryKeys(null, null, tableName.toUpperCase());
        while (rs.next()) {
            primaryKeyList.add(rs.getString("COLUMN_NAME"));
        }
    }finally{
        JdbcUtils.closeResultSet(rs);
        JdbcUtils.closeStatement(stmt);
        JdbcUtils.closeConnection(con);
    }
    return primaryKeyList;
}
项目:lodsve-framework    文件:MyBatisUtils.java   
public static int queryForInt(DataSource dataSource, String sql, Object... params) throws SQLException {
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
        ps = DataSourceUtils.doGetConnection(dataSource).prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            ps.setObject(i + 1, params[i]);
        }

        rs = ps.executeQuery();
        if (rs.next()) {
            return rs.getInt(1);
        } else {
            return -1;
        }
    } finally {
        if (ps != null) {
            ps.close();
        }
        if (rs != null) {
            rs.close();
        }
    }
}
项目:lodsve-framework    文件:AbstractDialect.java   
@Override
public boolean existTable(String tableName, DataSource dataSource) throws Exception {
    Assert.notNull(dataSource);
    Assert.hasText(tableName);

    String name = dataSource.getConnection().getCatalog();
    PreparedStatement ps = null;
    ResultSet resultSet = null;

    try {
        ps = DataSourceUtils.doGetConnection(dataSource).prepareStatement(existTableSql(name, tableName));
        resultSet = ps.executeQuery();

        return resultSet.next() && resultSet.getInt("count") > 0;
    } finally {
        if (ps != null) {
            ps.close();
        }
        if (resultSet != null) {
            resultSet.close();
        }
    }
}
项目:hsweb-framework    文件:DynamicSpringManagedTransaction.java   
@Override
public Connection getConnection() throws SQLException {
    TransactionProxy proxy = getProxy();
    if (proxy != null) {
        return proxy.getConnection();
    }
    //根据当前激活的数据源 获取jdbc链接
    DataSource dataSource = DataSourceHolder.currentDataSource().getNative();
    String dsId = switcher().currentDataSourceId();
    Connection connection = DataSourceUtils.getConnection(dataSource);
    proxy = new TransactionProxy(dsId, connection, dataSource);
    addProxy(proxy);

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(
                "DataSource (" + (dsId == null ? "default" : dsId) + ") JDBC Connection ["
                        + connection
                        + "] will"
                        + (proxy.isConnectionTransactional ? " " : " not ")
                        + "be managed by Spring");
    }

    return connection;
}
项目:spring4-understanding    文件:DatabasePopulatorUtils.java   
/**
 * Execute the given {@link DatabasePopulator} against the given {@link DataSource}.
 * @param populator the {@code DatabasePopulator} to execute
 * @param dataSource the {@code DataSource} to execute against
 * @throws DataAccessException if an error occurs, specifically a {@link ScriptException}
 */
public static void execute(DatabasePopulator populator, DataSource dataSource) throws DataAccessException {
    Assert.notNull(populator, "DatabasePopulator must be provided");
    Assert.notNull(dataSource, "DataSource must be provided");
    try {
        Connection connection = DataSourceUtils.getConnection(dataSource);
        try {
            populator.populate(connection);
        }
        finally {
            if (connection != null) {
                DataSourceUtils.releaseConnection(connection, dataSource);
            }
        }
    }
    catch (Exception ex) {
        if (ex instanceof ScriptException) {
            throw (ScriptException) ex;
        }

        throw new UncategorizedScriptException("Failed to execute database script", ex);
    }
}
项目:spring4-understanding    文件:AbstractSequenceMaxValueIncrementer.java   
/**
 * Executes the SQL as specified by {@link #getSequenceQuery()}.
 */
@Override
protected long getNextKey() throws DataAccessException {
    Connection con = DataSourceUtils.getConnection(getDataSource());
    Statement stmt = null;
    ResultSet rs = null;
    try {
        stmt = con.createStatement();
        DataSourceUtils.applyTransactionTimeout(stmt, getDataSource());
        rs = stmt.executeQuery(getSequenceQuery());
        if (rs.next()) {
            return rs.getLong(1);
        }
        else {
            throw new DataAccessResourceFailureException("Sequence query did not return a result");
        }
    }
    catch (SQLException ex) {
        throw new DataAccessResourceFailureException("Could not obtain sequence value", ex);
    }
    finally {
        JdbcUtils.closeResultSet(rs);
        JdbcUtils.closeStatement(stmt);
        DataSourceUtils.releaseConnection(con, getDataSource());
    }
}
项目:spring4-understanding    文件:NativeJdbcExtractorAdapter.java   
/**
 * Check for a ConnectionProxy chain, then delegate to doGetNativeConnection.
 * <p>ConnectionProxy is used by Spring's TransactionAwareDataSourceProxy
 * and LazyConnectionDataSourceProxy. The target connection behind it is
 * typically one from a local connection pool, to be unwrapped by the
 * doGetNativeConnection implementation of a concrete subclass.
 * @see #doGetNativeConnection
 * @see org.springframework.jdbc.datasource.ConnectionProxy
 * @see org.springframework.jdbc.datasource.DataSourceUtils#getTargetConnection
 * @see org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy
 * @see org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy
 */
@Override
public Connection getNativeConnection(Connection con) throws SQLException {
    if (con == null) {
        return null;
    }
    Connection targetCon = DataSourceUtils.getTargetConnection(con);
    Connection nativeCon = doGetNativeConnection(targetCon);
    if (nativeCon == targetCon) {
        // We haven't received a different Connection, so we'll assume that there's
        // some additional proxying going on. Let's check whether we get something
        // different back from the DatabaseMetaData.getConnection() call.
        DatabaseMetaData metaData = targetCon.getMetaData();
        // The following check is only really there for mock Connections
        // which might not carry a DatabaseMetaData instance.
        if (metaData != null) {
            Connection metaCon = metaData.getConnection();
            if (metaCon != null && metaCon != targetCon) {
                // We've received a different Connection there:
                // Let's retry the native extraction process with it.
                nativeCon = doGetNativeConnection(metaCon);
            }
        }
    }
    return nativeCon;
}
项目:bamboobsc    文件:HibernateExtendedJpaDialect.java   
@Override
 public Object beginTransaction(final EntityManager entityManager, 
        final TransactionDefinition definition) throws PersistenceException, SQLException, TransactionException {

    Session session = (Session) entityManager.getDelegate();
    if (definition.getTimeout() != TransactionDefinition.TIMEOUT_DEFAULT) {
        getSession(entityManager).getTransaction().setTimeout(definition.getTimeout());
    }
    entityManager.getTransaction().begin();
    logger.debug("Transaction started");
    session.doWork(new Work() {
@Override
public void execute(Connection connection) throws SQLException {
     logger.debug("The connection instance is " + connection.toString());
     logger.debug("The isolation level of the connection is " + connection.getTransactionIsolation() 
             + " and the isolation level set on the transaction is " + definition.getIsolationLevel() );
     DataSourceUtils.prepareConnectionForTransaction(connection, definition);
}
    });
    return prepareTransaction(entityManager, definition.isReadOnly(), definition.getName());
 }
项目:blog-java2    文件:SpringTestBase.java   
protected void executeSql(String path) {
    logger.info("executeSql : " + path);

    Resource resource = new ClassPathResource(path, getClass());
    ResourceDatabasePopulator rdp = new ResourceDatabasePopulator();
    rdp.addScript(resource);
    rdp.setSqlScriptEncoding("UTF-8");
    rdp.setIgnoreFailedDrops(true);
    rdp.setContinueOnError(false);

    try (Connection conn = DataSourceUtils.getConnection(dataSource)) {
        rdp.populate(conn);
    }
    catch (Exception e) {
        throw new IllegalStateException("executeSql failed, path=" + path, e);
    }
}
项目:ignite    文件:CacheSpringStoreSessionListenerSelfTest.java   
/**
 */
private void checkConnection() {
    Connection conn = DataSourceUtils.getConnection(jdbc.getDataSource());

    assertNotNull(conn);

    try {
        assertFalse(conn.isClosed());
        assertEquals(!ses.isWithinTransaction(), conn.getAutoCommit());
    }
    catch (SQLException e) {
        throw new RuntimeException(e);
    }

    verifySameInstance(conn);
}
项目:welshare    文件:HibernateExtendedJpaDialect.java   
@Override
public Object beginTransaction(EntityManager entityManager,
        final TransactionDefinition definition) throws PersistenceException,
        SQLException, TransactionException {

    Session session = entityManager.unwrap(Session.class);
    session.doWork(new Work() {
        @Override
        public void execute(Connection connection) throws SQLException {
            DataSourceUtils.prepareConnectionForTransaction(connection, definition);
            if (connection.isReadOnly() && !definition.isReadOnly()) {
                connection.setReadOnly(false);

            }
        }
    });

    entityManager.getTransaction().begin();

    return prepareTransaction(entityManager, definition.isReadOnly(), definition.getName());
}
项目:kansalaisaloite    文件:JdbcConfiguration.java   
@Bean
public PostgresQueryFactory queryFactory() {
    final DataSource dataSource = dataSource();
    return new PostgresQueryFactory(querydslConfiguration(), new Provider<Connection>() {

        @Override
        public Connection get() {
          Connection conn = DataSourceUtils.getConnection(dataSource);
          if (!DataSourceUtils.isConnectionTransactional(conn, dataSource)) {
              throw new RuntimeException("Connection is not transactional");
          }
          return conn;
        }

    });
}
项目:class-guard    文件:DatabasePopulatorUtils.java   
/**
 * Execute the given DatabasePopulator against the given DataSource.
 * @param populator the DatabasePopulator to execute
 * @param dataSource the DataSource to execute against
 */
public static void execute(DatabasePopulator populator, DataSource dataSource) {
    Assert.notNull(populator, "DatabasePopulator must be provided");
    Assert.notNull(dataSource, "DataSource must be provided");
    try {
        Connection connection = DataSourceUtils.getConnection(dataSource);
        try {
            populator.populate(connection);
        }
        finally {
            if (connection != null) {
                DataSourceUtils.releaseConnection(connection, dataSource);
            }
        }
    }
    catch (Exception ex) {
        throw new DataAccessResourceFailureException("Failed to execute database script", ex);
    }
}
项目:class-guard    文件:AbstractSequenceMaxValueIncrementer.java   
/**
 * Executes the SQL as specified by {@link #getSequenceQuery()}.
 */
@Override
protected long getNextKey() throws DataAccessException {
    Connection con = DataSourceUtils.getConnection(getDataSource());
    Statement stmt = null;
    ResultSet rs = null;
    try {
        stmt = con.createStatement();
        DataSourceUtils.applyTransactionTimeout(stmt, getDataSource());
        rs = stmt.executeQuery(getSequenceQuery());
        if (rs.next()) {
            return rs.getLong(1);
        }
        else {
            throw new DataAccessResourceFailureException("Sequence query did not return a result");
        }
    }
    catch (SQLException ex) {
        throw new DataAccessResourceFailureException("Could not obtain sequence value", ex);
    }
    finally {
        JdbcUtils.closeResultSet(rs);
        JdbcUtils.closeStatement(stmt);
        DataSourceUtils.releaseConnection(con, getDataSource());
    }
}
项目:class-guard    文件:NativeJdbcExtractorAdapter.java   
/**
 * Check for a ConnectionProxy chain, then delegate to doGetNativeConnection.
 * <p>ConnectionProxy is used by Spring's TransactionAwareDataSourceProxy
 * and LazyConnectionDataSourceProxy. The target connection behind it is
 * typically one from a local connection pool, to be unwrapped by the
 * doGetNativeConnection implementation of a concrete subclass.
 * @see #doGetNativeConnection
 * @see org.springframework.jdbc.datasource.ConnectionProxy
 * @see org.springframework.jdbc.datasource.DataSourceUtils#getTargetConnection
 * @see org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy
 * @see org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy
 */
public Connection getNativeConnection(Connection con) throws SQLException {
    if (con == null) {
        return null;
    }
    Connection targetCon = DataSourceUtils.getTargetConnection(con);
    Connection nativeCon = doGetNativeConnection(targetCon);
    if (nativeCon == targetCon) {
        // We haven't received a different Connection, so we'll assume that there's
        // some additional proxying going on. Let's check whether we get something
        // different back from the DatabaseMetaData.getConnection() call.
        DatabaseMetaData metaData = targetCon.getMetaData();
        // The following check is only really there for mock Connections
        // which might not carry a DatabaseMetaData instance.
        if (metaData != null) {
            Connection metaCon = metaData.getConnection();
            if (metaCon != null && metaCon != targetCon) {
                // We've received a different Connection there:
                // Let's retry the native extraction process with it.
                nativeCon = doGetNativeConnection(metaCon);
            }
        }
    }
    return nativeCon;
}
项目:syncope    文件:ProvisioningImpl.java   
@Override
public String delete(final String accountid) throws ProvisioningException {
    LOG.debug("Delete request received");

    Connection conn = null;
    try {
        conn = DataSourceUtils.getConnection(dataSource);

        try (PreparedStatement statement = conn.prepareStatement("DELETE FROM user WHERE userId=?")) {
            statement.setString(1, accountid);

            String query = "DELETE FROM user WHERE userId='" + accountid + "';";
            LOG.debug("Execute query: " + query);

            statement.executeUpdate();
        }

        return accountid;
    } catch (SQLException e) {
        throw new ProvisioningException("Delete operation failed", e);
    } finally {
        DataSourceUtils.releaseConnection(conn, dataSource);
    }
}
项目:syncope    文件:JobManagerImpl.java   
private boolean isRunningElsewhere(final JobKey jobKey) throws SchedulerException {
    if (!scheduler.getScheduler().getMetaData().isJobStoreClustered()) {
        return false;
    }

    DataSource dataSource = domainsHolder.getDomains().get(SyncopeConstants.MASTER_DOMAIN);
    Connection conn = DataSourceUtils.getConnection(dataSource);
    PreparedStatement stmt = null;
    ResultSet resultSet = null;
    try {
        stmt = conn.prepareStatement(
                "SELECT 1 FROM " + Constants.DEFAULT_TABLE_PREFIX + "FIRED_TRIGGERS "
                + "WHERE JOB_NAME = ? AND JOB_GROUP = ?");
        stmt.setString(1, jobKey.getName());
        stmt.setString(2, jobKey.getGroup());

        resultSet = stmt.executeQuery();
        return resultSet.next();
    } catch (SQLException e) {
        throw new SchedulerException(e);
    } finally {
        IOUtil.quietClose(resultSet);
        IOUtil.quietClose(stmt);
        DataSourceUtils.releaseConnection(conn, dataSource);
    }
}
项目:SpringClips    文件:PersistenceConfigurarion.java   
@Bean
@Lazy(false)
public ResourceDatabasePopulator populateDatabase() throws SQLException {
    final ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    populator.addScript(new ClassPathResource("data.sql"));

    Connection connection = null;

    try {
        connection = DataSourceUtils.getConnection(dataSource());
        populator.populate(connection);
    } finally {
        if (connection != null) {
            DataSourceUtils.releaseConnection(connection, dataSource());
        }
    }

    return populator;
}
项目:oblatum    文件:SqlGenerator.java   
public List<Column> getColumns(String tableName) throws SQLException {
    List<Column> columns = new ArrayList<Column>();
    Connection connection = DataSourceUtils.getConnection(dataSource);
    DatabaseMetaData metaData = connection.getMetaData();
    ResultSet columnsResultSet = metaData.getColumns(null, metaData.getUserName(), tableName, "%");
    while (columnsResultSet.next()) {
        Column column = new Column();
        column.setColumnName(columnsResultSet.getString("COLUMN_NAME").toLowerCase());
        column.setDataType(columnsResultSet.getInt("DATA_TYPE"));
        column.setTypeName(columnsResultSet.getString("TYPE_NAME"));
        column.setColumnSize(columnsResultSet.getInt("COLUMN_SIZE"));
        column.setNullable(columnsResultSet.getInt("NULLABLE"));
        column.setRemarks(columnsResultSet.getString("REMARKS"));
        column.setColumnDef(columnsResultSet.getString("COLUMN_DEF"));
        column.setOrdinalPosition(columnsResultSet.getInt("ORDINAL_POSITION"));
        column.setIsNullable(columnsResultSet.getString("IS_NULLABLE"));
        column.setIsAutoincrement(columnsResultSet.getString("IS_AUTOINCREMENT"));
        columns.add(column);
    }
    DataSourceUtils.releaseConnection(connection, dataSource);
    return columns;
}
项目:cobarclient    文件:DefaultConcurrentRequestProcessor.java   
private List<RequestDepository> fetchConnectionsAndDepositForLaterUse(
                                                                      List<ConcurrentRequest> requests) {
    List<RequestDepository> depos = new ArrayList<RequestDepository>();
    for (ConcurrentRequest request : requests) {
        DataSource dataSource = request.getDataSource();

        Connection springCon = null;
        boolean transactionAware = (dataSource instanceof TransactionAwareDataSourceProxy);
        try {
            springCon = (transactionAware ? dataSource.getConnection() : DataSourceUtils
                    .doGetConnection(dataSource));
        } catch (SQLException ex) {
            throw new CannotGetJdbcConnectionException("Could not get JDBC Connection", ex);
        }

        RequestDepository depo = new RequestDepository();
        depo.setOriginalRequest(request);
        depo.setConnectionToUse(springCon);
        depo.setTransactionAware(transactionAware);
        depos.add(depo);
    }

    return depos;
}
项目:bandwidth-on-demand    文件:HibernateJpaDialectWithTransactionIsolationSupport.java   
@Override
public Object beginTransaction(EntityManager entityManager, TransactionDefinition definition)
    throws PersistenceException, SQLException, TransactionException {

  Session session = (Session) entityManager.getDelegate();
  if (definition.getTimeout() != TransactionDefinition.TIMEOUT_DEFAULT) {
    getSession(entityManager).getTransaction().setTimeout(definition.getTimeout());
  }

  Connection connection = ((SessionImpl) session).connection();
  Integer previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(connection, definition);

  entityManager.getTransaction().begin();

  Object transactionDataFromHibernateJpaDialect = prepareTransaction(entityManager, definition.isReadOnly(), definition.getName());
  return new IsolationSupportSessionTransactionData(transactionDataFromHibernateJpaDialect, previousIsolationLevel, connection);
}
项目:CommonDao    文件:JdbcTxCommonDao.java   
/**
 * 添加支持jdbc datasource Transaction 支持的QueryRunner处理方式
 */
@Override
protected QueryRunner getQueryRunner() {

    return new QueryRunner(dataSource){

        /* (non-Javadoc)
         * @see org.apache.commons.dbutils.AbstractQueryRunner#prepareConnection()
         */
        @Override
        protected Connection prepareConnection() throws SQLException {
            return DataSourceUtils.getConnection(this.getDataSource());
        }

        /* (non-Javadoc)
         * @see org.apache.commons.dbutils.AbstractQueryRunner#close(java.sql.Connection)
         */
        @Override
        protected void close(Connection conn) throws SQLException {
            DataSourceUtils.releaseConnection(conn, getDataSource());
        }

    };
}
项目:replyit-master-3.2-final    文件:RateCardBL.java   
/**
 * Returns a list of column names read from the rate table in the database.
 * @return column names
 */
public List<String> getRateTableColumnNames() {
    DataSource dataSource = jdbcTemplate.getDataSource();
    Connection connection = DataSourceUtils.getConnection(dataSource);

    List<String> columns = Collections.emptyList();

    try {
        columns = JDBCUtils.getAllColumnNames(connection, rateCard.getTableName());
    } catch (SQLException e) {
        throw new SessionInternalError("Could not read columns from rate card table.", e,
                                       new String[] { "RateCardWS,rates,rate.card.cannot.read.rating.table" });

    } finally {
        DataSourceUtils.releaseConnection(connection, dataSource);
    }

    return columns;
}
项目:replyit-master-3.2-final    文件:HSQLDBCacheTest.java   
public void testLoader() throws Exception {
    assertEquals("rules_table", loader.getTableName());

    // count the number of records loaded
    DataSource dataSource = getDataSource();
    Connection connection = DataSourceUtils.getConnection(dataSource);

    Statement statement = connection.createStatement();
    ResultSet result = statement.executeQuery("select count(*) as REC_COUNT from " + loader.getTableName());
    result.next();

    long recordsCount = result.getLong("REC_COUNT");

    assertTrue("Loader successfully populated records in the database",recordsCount > 0);
    assertEquals("Loaded correct number of records", 1769, recordsCount);

    // cleanup
    result.close();
    statement.close();
    DataSourceUtils.releaseConnection(connection, dataSource);
}
项目:jkami    文件:RunConfing.java   
public Connection getConnection() {
    if (dataSource == null) {
        throw new RuntimeException("dataSource is null  no bean dataSource please set spring xml ");
    }
    try {
        return DataSourceUtils.getConnection(dataSource);
    } catch (CannotGetJdbcConnectionException e) {
        try {
            return dataSource.getConnection();
        } catch (SQLException e1) {
            throw new JkException(e);
        }
    }
}
项目:jkami    文件:RunConfing.java   
public void doReleaseConnection(Connection con) {
    try {
        if (dataSource != null) {
            DataSourceUtils.doReleaseConnection(con, dataSource);
        } else {
            con.close();
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
项目:Equella    文件:JDBCOdaResultSet.java   
@Override
public void close() throws OdaException
{
    try
    {
        if( resultSet != null )
        {
            resultSet.close();
        }
        if( statement != null )
        {
            statement.close();
        }
        if( connection != null )
        {
            DataSourceUtils.releaseConnection(connection, dataSource);
        }
        statement = null;
        connection = null;
        dataSource = null;
        rowData = null;
        resultSet = null;
    }
    catch( SQLException e )
    {
        throw new OdaException(e);
    }
}
项目:lams    文件:JdbcTemplate.java   
@Override
public <T> T execute(ConnectionCallback<T> action) throws DataAccessException {
    Assert.notNull(action, "Callback object must not be null");

    Connection con = DataSourceUtils.getConnection(getDataSource());
    try {
        Connection conToUse = con;
        if (this.nativeJdbcExtractor != null) {
            // Extract native JDBC Connection, castable to OracleConnection or the like.
            conToUse = this.nativeJdbcExtractor.getNativeConnection(con);
        }
        else {
            // Create close-suppressing Connection proxy, also preparing returned Statements.
            conToUse = createConnectionProxy(con);
        }
        return action.doInConnection(conToUse);
    }
    catch (SQLException ex) {
        // Release Connection early, to avoid potential connection pool deadlock
        // in the case when the exception translator hasn't been initialized yet.
        DataSourceUtils.releaseConnection(con, getDataSource());
        con = null;
        throw getExceptionTranslator().translate("ConnectionCallback", getSql(action), ex);
    }
    finally {
        DataSourceUtils.releaseConnection(con, getDataSource());
    }
}
项目:lams    文件:JdbcTemplate.java   
@Override
public <T> T execute(StatementCallback<T> action) throws DataAccessException {
    Assert.notNull(action, "Callback object must not be null");

    Connection con = DataSourceUtils.getConnection(getDataSource());
    Statement stmt = null;
    try {
        Connection conToUse = con;
        if (this.nativeJdbcExtractor != null &&
                this.nativeJdbcExtractor.isNativeConnectionNecessaryForNativeStatements()) {
            conToUse = this.nativeJdbcExtractor.getNativeConnection(con);
        }
        stmt = conToUse.createStatement();
        applyStatementSettings(stmt);
        Statement stmtToUse = stmt;
        if (this.nativeJdbcExtractor != null) {
            stmtToUse = this.nativeJdbcExtractor.getNativeStatement(stmt);
        }
        T result = action.doInStatement(stmtToUse);
        handleWarnings(stmt);
        return result;
    }
    catch (SQLException ex) {
        // Release Connection early, to avoid potential connection pool deadlock
        // in the case when the exception translator hasn't been initialized yet.
        JdbcUtils.closeStatement(stmt);
        stmt = null;
        DataSourceUtils.releaseConnection(con, getDataSource());
        con = null;
        throw getExceptionTranslator().translate("StatementCallback", getSql(action), ex);
    }
    finally {
        JdbcUtils.closeStatement(stmt);
        DataSourceUtils.releaseConnection(con, getDataSource());
    }
}
项目:lams    文件:JdbcTemplate.java   
/**
 * Prepare the given JDBC Statement (or PreparedStatement or CallableStatement),
 * applying statement settings such as fetch size, max rows, and query timeout.
 * @param stmt the JDBC Statement to prepare
 * @throws SQLException if thrown by JDBC API
 * @see #setFetchSize
 * @see #setMaxRows
 * @see #setQueryTimeout
 * @see org.springframework.jdbc.datasource.DataSourceUtils#applyTransactionTimeout
 */
protected void applyStatementSettings(Statement stmt) throws SQLException {
    int fetchSize = getFetchSize();
    if (fetchSize > 0) {
        stmt.setFetchSize(fetchSize);
    }
    int maxRows = getMaxRows();
    if (maxRows > 0) {
        stmt.setMaxRows(maxRows);
    }
    DataSourceUtils.applyTimeout(stmt, getDataSource(), getQueryTimeout());
}
项目:lams    文件:LocalDataSourceConnectionProvider.java   
/**
 * This implementation calls {@link DataSourceUtils#doCloseConnection},
 * checking against a {@link org.springframework.jdbc.datasource.SmartDataSource}.
 */
@Override
public void closeConnection(Connection con) throws SQLException {
    try {
        DataSourceUtils.doCloseConnection(con, this.dataSourceToUse);
    }
    catch (SQLException ex) {
        JDBCExceptionReporter.logExceptions(ex);
        throw ex;
    }
}
项目:OperatieBRP    文件:ZoekPersoonRepositoryImpl.java   
@Override
public boolean isPostgres() throws SQLException {
    Connection connection = null;
    try {
        connection = DataSourceUtils.getConnection(masterDataSource);
        final String url = connection.getMetaData().getURL();
        return url.contains("postgres");
    } finally {
        DataSourceUtils.releaseConnection(connection, masterDataSource);
    }
}