當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。