当前位置: 首页>>代码示例>>Java>>正文


Java BasicDataSource.getConnection方法代码示例

本文整理汇总了Java中org.apache.commons.dbcp2.BasicDataSource.getConnection方法的典型用法代码示例。如果您正苦于以下问题:Java BasicDataSource.getConnection方法的具体用法?Java BasicDataSource.getConnection怎么用?Java BasicDataSource.getConnection使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在org.apache.commons.dbcp2.BasicDataSource的用法示例。


在下文中一共展示了BasicDataSource.getConnection方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: getValue

import org.apache.commons.dbcp2.BasicDataSource; //导入方法依赖的package包/类
public static String getValue(String databasePath, String table, String id)
{
	if(!validate(table))
	{	return null; }
	Connection conn = null;
	String val = null;
	try
	{
		BasicDataSource ds = getDataSource(databasePath);
		if(ds == null)
		{	return val; }
		conn = ds.getConnection();
		PreparedStatement s = conn.prepareStatement("select json from " + table + " where id=?");
		s.setString(1, id);
		ResultSet rs = s.executeQuery();
		if(rs.next())
		{	val = rs.getString(1); }
		rs.close();
		s.close();
	} catch(Exception e) {
		// log?
	} finally {
		if(conn != null)
		{	try { conn.close(); } catch(SQLException sqle) { } }
	} return val;
}
 
开发者ID:zueski,项目名称:playswith,代码行数:27,代码来源:ManifestCache.java

示例2: openConnection

import org.apache.commons.dbcp2.BasicDataSource; //导入方法依赖的package包/类
public static IDatabaseConnection openConnection(final BasicDataSource ds) {
    try {
        final Connection connection = ds.getConnection();

        for (final DbUnitConnectionFactory impl : SERVICE_LOADER) {
            if (impl.supportsDriver(ds.getDriverClassName())) {
                return impl.createConnection(connection);
            }
        }

        // fall back if no specific implementation is available
        return new DatabaseConnection(connection);
    } catch (final DatabaseUnitException | SQLException e) {
        throw new JpaUnitException(e);
    }
}
 
开发者ID:dadrus,项目名称:jpa-unit,代码行数:17,代码来源:DatabaseConnectionFactory.java

示例3: getConnection

import org.apache.commons.dbcp2.BasicDataSource; //导入方法依赖的package包/类
/**
 * @return Connection
 * @throws SQLException if database access error occurrs
 */
public Connection getConnection() throws SQLException {
    Connection conn = null;
    BasicDataSource dsc = null;
    if (sharedDSC != null){ // i.e. shared pool
        dsc = sharedDSC;
    } else {
        Map<String, BasicDataSource> poolMap = perThreadPoolMap.get();
        dsc = poolMap.get(getDataSourceName());
        if (dsc == null){
            dsc = initPool("1");
            poolMap.put(getDataSourceName(),dsc);
            log.debug("Storing pool: "+getName()+" @"+System.identityHashCode(dsc));
            perThreadPoolSet.add(dsc);
        }
    }
    if (dsc != null) {
        conn=dsc.getConnection();
        int transactionIsolation = DataSourceElementBeanInfo.getTransactionIsolationMode(getTransactionIsolation());
        if (transactionIsolation >= 0 && conn.getTransactionIsolation() != transactionIsolation) {
            try {
                // make sure setting the new isolation mode is done in an auto committed transaction
                conn.setTransactionIsolation(transactionIsolation);
                log.debug("Setting transaction isolation: " + transactionIsolation + " @"
                        + System.identityHashCode(dsc));
            } catch (SQLException ex) {
                log.error("Could not set transaction isolation: " + transactionIsolation + " @"
                        + System.identityHashCode(dsc));
            }   
        }
    }
    return conn;
}
 
开发者ID:johrstrom,项目名称:cloud-meter,代码行数:37,代码来源:DataSourceElement.java

示例4: get

import org.apache.commons.dbcp2.BasicDataSource; //导入方法依赖的package包/类
public static Connection get(String Id, String userId, String userPswd)
throws Exception
  {
    if (userId == null)
      LOG.info(QueryDetails._LOGGING_HEADER + "G E T T I N G   C O N N E C T I O N  -----  " + Id);
    else
      LOG.info(QueryDetails._LOGGING_HEADER + "G E T T I N G   U N P O O L E D   C O N N E C T I O N   W I T H   U S E R   O V E R R I D E  (" + userId + ")-----  " + Id);
    BasicDataSource BDS = _DataSourcesById.get(Id);
    if (BDS == null)
      throw new Exception("Cannot find a connection pool for " + Id);

    java.sql.Connection C = null;
    for (int i = 1; i < 100; ++i)
      {
        try
          {
            long T0 = System.nanoTime();
            if (userId == null)
              C = BDS.getConnection();
            else
              {
                Class.forName(BDS.getDriverClassName());
                C = DriverManager.getConnection(BDS.getUrl(), userId, userPswd);
                C.setAutoCommit(false);
                C.setTransactionIsolation(java.sql.Connection.TRANSACTION_READ_COMMITTED);
              }
            PerfTracker.add(TransactionType.CONNECTION_GET, System.nanoTime() - T0);
            break;
          }
        catch (SQLException E)
          {
            LOG.error("   - Attempt #" + i + " failed to obtain a connection: " + E.getMessage());
            if (Migrate.isTesting() == true)
              {
                if (C != null)
                  C.close();
                throw E;
              }
            if (i == 1)
              LOG.error("     (Sleeping for 30 seconds, and will re-try again, for a max of 100 times)");
            Thread.sleep(1000 * 30);
          }
      }
    if (C == null)
      throw new Exception("Failed obtaining a connection after numerous tries.");
    Connection Conn = new Connection(C, Id);
    LOG.info(QueryDetails._LOGGING_HEADER + "G O T           C O N N E C T I O N  -----  " + Conn._PoolId + ", " + BDS.getNumActive() + "/" + BDS.getNumIdle() + "/" + BDS.getMaxTotal());
    return Conn;
  }
 
开发者ID:CapsicoHealth,项目名称:Tilda,代码行数:50,代码来源:ConnectionPool.java

示例5: generateSaveAndGetAPIToken

import org.apache.commons.dbcp2.BasicDataSource; //导入方法依赖的package包/类
private Token generateSaveAndGetAPIToken(BasicDataSource dataSource, User user) {

		Token apiToken = null;

		try (Connection dbConnection = dataSource.getConnection()) {

			apiToken = generateRandomTokenFromUserInfo(user, TokenTypes.API_KEY_TOKEN_TYPE.getTypeNumber());
			tokenDAO.createToken(dbConnection, apiToken);
			tokenCacheDao.addTokenUsingTokenValueAsKey(apiToken);

		} catch (TokenGenerationException | SQLException e) {

			LOGGER.error("generateSaveAndGetAPIToken", e);
			throw new IllegalStateException(e);

		}

		return apiToken;
	}
 
开发者ID:granpanda,项目名称:autheo,代码行数:20,代码来源:TokenBusiness.java

示例6: generateSaveAndGetInternalAPIToken

import org.apache.commons.dbcp2.BasicDataSource; //导入方法依赖的package包/类
private Token generateSaveAndGetInternalAPIToken(BasicDataSource dataSource, User user) {

		Token internalAPIToken = null;

		try (Connection dbConnection = dataSource.getConnection()) {

			internalAPIToken = generateRandomTokenFromUserInfo(user, INTERNAL_API_CLIENT_ROLE, TokenTypes.INTERNAL_API_TOKEN_TYPE.getTypeNumber());
			tokenDAO.createToken(dbConnection, internalAPIToken);
			tokenCacheDao.addTokenUsingTokenValueAsKey(internalAPIToken);
			tokenCacheDao.addTokenUsingOrganizationAsKey(internalAPIToken);

		} catch (TokenGenerationException | SQLException e) {

			LOGGER.error("generateSaveAndGetInternalAPIToken", e);
			throw new IllegalStateException(e);

		}

		return internalAPIToken;
	}
 
开发者ID:granpanda,项目名称:autheo,代码行数:21,代码来源:TokenBusiness.java

示例7: getDataBaseConnection

import org.apache.commons.dbcp2.BasicDataSource; //导入方法依赖的package包/类
public static Connection getDataBaseConnection ( String linkName, DataOfDataBaseLink link, boolean doPreLoadClass ) throws Exception {
  	
  	if ( doPreLoadClass && ! "" . equals ( link . preLoadClassName ) ) {
  		
  		 Class . forName ( link . preLoadClassName ) . newInstance ( ) ;
  		 
  	}
  	
BasicDataSource bds = new BasicDataSource ( ) ;

  	if ( link . hasCustomLink ) {

  		bds . setUrl ( link . customLink . replace ( "%host%", link . host ) . replace ( "%port%", Integer . toString ( link . port ) ) . replace ( "%name%", link . name ) + ( link . useUTF8 ? "?useUnicode=true&characterEncoding=UTF-8" : "" ) ) ;
		
  	} else {
  		
  		bds . setUrl (  "jdbc:mysql://" + link . host + ":" + link . port + "/" + link . name + ( link . useUTF8 ? "?useUnicode=true&characterEncoding=UTF-8" : "" ) ) ;
  		    		
  	}
  	
if ( ! "" . equals ( link . user ) && ! "" . equals ( link . password ) ) {
	
	bds . setUsername ( link . user ) ;
	bds . setPassword ( link . password ) ;
	
}

dataBaseSources . put ( linkName, bds ) ;

  	return bds . getConnection ( ) ;
  	
  }
 
开发者ID:Pishka,项目名称:MineDonate,代码行数:33,代码来源:ModDataBase.java

示例8: findCoordinates

import org.apache.commons.dbcp2.BasicDataSource; //导入方法依赖的package包/类
public BinlogCoordinates findCoordinates(String gtid) {

        BasicDataSource source = new BasicDataSource();

        source.setDriverClassName("com.mysql.jdbc.Driver");
        source.setUsername(username);
        source.setPassword(password);
        source.setUrl( String.format("jdbc:mysql://%s:%s", host, port) );
        source.addConnectionProperty("useUnicode", "true");
        source.addConnectionProperty("characterEncoding", "UTF-8");

        try ( Connection connection = source.getConnection() ){

            String file = findFile(gtid, connection);

            LOGGER.info("Getting GTID position in the file {}", file);

            long position = findPosition(gtid, file, connection);

            return new BinlogCoordinates(file,position);

        } catch (SQLException | QueryInspectorException e) {

            LOGGER.error("Failed to find binlog coordinates for gtid ", e);

            throw new RuntimeException(e);

        }

    }
 
开发者ID:mysql-time-machine,项目名称:replicator,代码行数:31,代码来源:BinlogCoordinatesFinder.java


注:本文中的org.apache.commons.dbcp2.BasicDataSource.getConnection方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。