java.sql.Driver Java Examples

The following examples show how to use java.sql.Driver. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: clearpool   Author: xionghuiCoder   File: DataSourceUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static CommonDataSource getJDBCDataSource(String clazz, String url, String user,
    String password) {
  if (url == null) {
    throw new ConnectionPoolException("url is null");
  }
  Driver driver;
  try {
    if (clazz == null) {
      clazz = JdbcUtils.getDriverClassName(url);
    }
    driver = JdbcUtils.createDriver(clazz);
  } catch (SQLException e) {
    throw new ConnectionPoolException(e);
  }
  Properties connectProperties = new Properties();
  if (user != null) {
    connectProperties.put("user", user);
  }
  if (password != null) {
    connectProperties.put("password", password);
  }
  return new JDBCDataSource(clazz, url, driver, connectProperties);
}
 
Example #2
Source Project: presto   Author: prestosql   File: TestPrestoDriver.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetDriverVersion()
        throws Exception
{
    Driver driver = DriverManager.getDriver("jdbc:presto:");
    assertEquals(driver.getMajorVersion(), 0);
    assertEquals(driver.getMajorVersion(), 0);

    try (Connection connection = createConnection()) {
        DatabaseMetaData metaData = connection.getMetaData();
        assertEquals(metaData.getDriverName(), PrestoDriver.DRIVER_NAME);
        assertEquals(metaData.getDriverVersion(), "unknown");
        assertEquals(metaData.getDriverMajorVersion(), 0);
        assertEquals(metaData.getDriverMinorVersion(), 0);
    }
}
 
Example #3
Source Project: obevo   Author: goldmansachs   File: JdbcDataSourceFactory.java    License: Apache License 2.0 6 votes vote down vote up
private static DataSource createFromJdbcUrl(Class<? extends Driver> driverClass, String url,
        Credential credential, int numThreads, ImmutableList<String> initSqls, Properties extraConnectionProperties) {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(driverClass.getName());
    // TODO validate non-null host name, notably for postgresl jdbc url
    dataSource.setUrl(url);
    dataSource.setUsername(credential.getUsername());
    dataSource.setPassword(credential.getPassword());

    // connection pool settings
    dataSource.setInitialSize(numThreads);
    dataSource.setMaxActive(numThreads);
    // keep the connections open if possible; only close them via the removeAbandonedTimeout feature
    dataSource.setMaxIdle(numThreads);
    dataSource.setMinIdle(0);
    dataSource.setRemoveAbandonedTimeout(300);

    dataSource.setConnectionInitSqls(initSqls.castToList());
    if (extraConnectionProperties != null) {
        for (String key : extraConnectionProperties.stringPropertyNames()) {
            dataSource.addConnectionProperty(key, extraConnectionProperties.getProperty(key));
        }
    }

    return dataSource;
}
 
Example #4
Source Project: mybatis-generator-core-fix   Author: liudongdong0909   File: ConnectionFactory.java    License: Apache License 2.0 6 votes vote down vote up
public Connection getConnection(JDBCConnectionConfiguration config)
        throws SQLException {
    Driver driver = getDriver(config);

    Properties props = new Properties();

    if (stringHasValue(config.getUserId())) {
        props.setProperty("user", config.getUserId()); //$NON-NLS-1$
    }

    if (stringHasValue(config.getPassword())) {
        props.setProperty("password", config.getPassword()); //$NON-NLS-1$
    }

    props.putAll(config.getProperties());

    Connection conn = driver.connect(config.getConnectionURL(), props);

    if (conn == null) {
        throw new SQLException(getString("RuntimeError.7")); //$NON-NLS-1$
    }

    return conn;
}
 
Example #5
Source Project: pentaho-metadata   Author: pentaho   File: BaseHiveDialect.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
protected synchronized void initDriverInfo() {
  Integer majorVersion = 0;
  Integer minorVersion = 0;

  try {
    // Load the driver version number
    Class<?> driverClass = Class.forName( getDriverClassName() ); //$NON-NLS-1$
    if ( driverClass != null ) {
      Driver driver = (Driver) driverClass.getConstructor().newInstance();
      majorVersion = driver.getMajorVersion();
      minorVersion = driver.getMinorVersion();
    }
  } catch ( Exception e ) {
    // Failed to load the driver version, leave at the defaults
  }

  driverMajorVersion = majorVersion;
  driverMinorVersion = minorVersion;
}
 
Example #6
Source Project: ClickHouse-Native-JDBC   Author: housepower   File: AbstractITest.java    License: Apache License 2.0 6 votes vote down vote up
protected void withNewConnection(WithConnection withConnection, Object... args)
    throws Exception {
    // deregisterDriver other jdbc drivers
    Enumeration<Driver> drivers = DriverManager.getDrivers();
    while (drivers.hasMoreElements()) {
        DriverManager.deregisterDriver(drivers.nextElement());
    }
    DriverManager.registerDriver(new ClickHouseDriver());

    String connectionStr = "jdbc:clickhouse://127.0.0.1:" + SERVER_PORT;

    // first arg is use_client_time_zone
    if (args.length > 0) {
        if (args[0].equals(true)) {
            connectionStr += "?use_client_time_zone=true";
        }
    }
    Connection connection = DriverManager.getConnection(connectionStr);
    try {
        withConnection.apply(connection);
    } finally {
        connection.close();
    }
}
 
Example #7
Source Project: dekaf   Author: JetBrains   File: CHouseIntermediateProvider.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected Driver loadDriver(final String connectionString) {
  Class<Driver> driverClass = getSimpleAccessibleDriverClass(CHOUSE_DRIVER_CLASS_NAME);
  if (driverClass == null) {
    // TODO try to load from jars
  }
  if (driverClass == null) {
    throw new DBInitializationException("ClickHouse SQL Driver class not found");
  }

  final Driver driver;
  try {
    driver = driverClass.newInstance();
  }
  catch (Exception e) {
    throw new DBPreparingException("Failed to instantiate driver: "+e.getMessage(), e);
  }

  return driver;
}
 
Example #8
Source Project: query2report   Author: yogeshsd   File: ConnectionFactory.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static Connection getConnection(String alias) {
	ConnectionParams params = ConnectionManager.getConnectionManager().getConnectionParams(alias);
	String url = params.getUrl();
	DriverParams driverParams = DriverManager.getDriverManager().getDriver(params.getDriver());
	String driverClass = driverParams.getClassName();
	String username = params.getUsername();
	String password = params.getPassword();
	String decPassword = EncryptionUtil.decrypt(password);
	logger.info("Trying to get connection to DB " + url + " for user " + username + " and driver class [" + driverClass + "]");
	try{
		Driver driver = (Driver) Class.forName(driverClass).newInstance();
		Properties props = new Properties();
		props.put("user", username);
		props.put("password", decPassword);
		Connection connection = driver.connect(url, props);
		connection.setAutoCommit(false);
		logger.info("Got new connection to DB " + url + " for user " + username);
		return connection;
	}catch (Throwable e){
		logger.error("Error getting connection to "+url+" for user "+username,e);
		return null;
	}
}
 
Example #9
Source Project: ormlite-jdbc   Author: j256   File: JdbcConnectionSourceTest.java    License: ISC License 6 votes vote down vote up
@Test(expected = SQLException.class)
public void testConnectionClosed() throws Exception {
	Connection conn = createMock(Connection.class);
	conn.setAutoCommit(true);
	expect(conn.isClosed()).andReturn(true);
	Driver driver = createMock(Driver.class);
	String url = "jdbc:bar:baz";
	expect(driver.acceptsURL(url)).andReturn(true);
	expect(driver.connect(isA(String.class), isA(Properties.class))).andReturn(conn);
	replay(driver, conn);
	DriverManager.registerDriver(driver);
	try {
		JdbcConnectionSource sds = new JdbcConnectionSource(url, databaseType);
		assertNotNull(sds.getReadOnlyConnection(null));
		sds.getReadOnlyConnection(null);
		sds.close();
		fail("Should not get here");
	} finally {
		DriverManager.deregisterDriver(driver);
	}
}
 
Example #10
Source Project: apiman   Author: apiman   File: BasicAuthJDBCTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates an in-memory datasource.
 * @throws SQLException
 */
private static BasicDataSource createInMemoryDatasource() throws SQLException {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(Driver.class.getName());
    ds.setUsername("sa"); //$NON-NLS-1$
    ds.setPassword(""); //$NON-NLS-1$
    ds.setUrl("jdbc:h2:mem:BasicAuthJDBCTest;DB_CLOSE_DELAY=-1"); //$NON-NLS-1$
    Connection connection = ds.getConnection();
    connection.prepareStatement("CREATE TABLE users ( username varchar(255) NOT NULL, password varchar(255) NOT NULL, PRIMARY KEY (username))").executeUpdate();
    connection.prepareStatement("INSERT INTO users (username, password) VALUES ('bwayne', 'ae2efd698aefdf366736a4eda1bc5241f9fbfec7')").executeUpdate();
    connection.prepareStatement("INSERT INTO users (username, password) VALUES ('ckent', 'ea59f7ca52a2087c99374caba0ff29be1b2dcdbf')").executeUpdate();
    connection.prepareStatement("INSERT INTO users (username, password) VALUES ('ballen', 'ea59f7ca52a2087c99374caba0ff29be1b2dcdbf')").executeUpdate();
    connection.prepareStatement("CREATE TABLE roles (rolename varchar(255) NOT NULL, username varchar(255) NOT NULL)").executeUpdate();
    connection.prepareStatement("INSERT INTO roles (rolename, username) VALUES ('user', 'bwayne')").executeUpdate();
    connection.prepareStatement("INSERT INTO roles (rolename, username) VALUES ('admin', 'bwayne')").executeUpdate();
    connection.prepareStatement("INSERT INTO roles (rolename, username) VALUES ('ckent', 'user')").executeUpdate();
    connection.prepareStatement("INSERT INTO roles (rolename, username) VALUES ('ballen', 'user')").executeUpdate();
    connection.close();
    return ds;
}
 
Example #11
Source Project: bamboobsc   Author: billchen198318   File: ContainerContextClosedMySqlDriversHandlerListener.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void contextDestroyed(ServletContextEvent contextEvent) {
	Enumeration<Driver> drivers = DriverManager.getDrivers();
	Driver driver = null;
	while(drivers.hasMoreElements()) {
		driver = drivers.nextElement();
		try {
			DriverManager.deregisterDriver(driver);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	/*
	try {
		AbandonedConnectionCleanupThread.shutdown();
	} catch (InterruptedException e) {
		e.printStackTrace();
	}		
	*/
	//AbandonedConnectionCleanupThread.checkedShutdown();
}
 
Example #12
Source Project: spring4-understanding   Author: langtianya   File: SimpleDriverDataSourceFactory.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ConnectionProperties getConnectionProperties() {
	return new ConnectionProperties() {
		@Override
		public void setDriverClass(Class<? extends Driver> driverClass) {
			dataSource.setDriverClass(driverClass);
		}

		@Override
		public void setUrl(String url) {
			dataSource.setUrl(url);
		}

		@Override
		public void setUsername(String username) {
			dataSource.setUsername(username);
		}

		@Override
		public void setPassword(String password) {
			dataSource.setPassword(password);
		}
	};
}
 
Example #13
Source Project: cacheonix-core   Author: cacheonix   File: DatabaseConnector.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Constructor.
 *
 * @param driverName JDBC driver name.
 * @param url        database URL
 * @param user       database user
 * @param password   database password
 * @throws IllegalArgumentException if the database driver cannot be loaded.
 */
public DatabaseConnector(final String driverName, final String url, final String user,
                         final String password)
        throws IllegalArgumentException {

   // Load driver
   try {
      final Class driverClass = Class.forName(driverName);
      driver = (Driver) driverClass.newInstance();
   } catch (final Exception e) {
      throw new IllegalArgumentException("Cannot set up database driver: " + e.toString());
   }

   // Set connection properties
   connectionUrl = url;
   connectionProperties = new Properties();
   connectionProperties.setProperty("user", user);
   connectionProperties.setProperty("password", password);
}
 
Example #14
Source Project: onedev   Author: theonedev   File: DefaultPersistManager.java    License: MIT License 6 votes vote down vote up
protected Connection getConnection() {
	try {
		Driver driver = (Driver) Class.forName(properties.getDriver(), true, 
				Thread.currentThread().getContextClassLoader()).newInstance();
		Properties connectProps = new Properties();
		String user = properties.getUser();
		String password = properties.getPassword();
        if (user != null) 
            connectProps.put("user", user);
        if (password != null) 
            connectProps.put("password", password);
		
		return driver.connect(properties.getUrl(), connectProps);
	} catch (Exception e) {
		throw ExceptionUtils.unchecked(e);
	}
}
 
Example #15
Source Project: dhis2-core   Author: dhis2   File: StartupListener.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void contextDestroyed( ServletContextEvent event )
{
    Enumeration<Driver> drivers = DriverManager.getDrivers();

    while ( drivers.hasMoreElements() )
    {
        Driver driver = drivers.nextElement();
        try
        {
            DriverManager.deregisterDriver( driver );
            log.info( "De-registering jdbc driver: " + driver );
        }
        catch ( SQLException e )
        {
            log.info( "Error de-registering driver " + driver + " :" + e.getMessage() );
        }
    }
}
 
Example #16
Source Project: pentaho-kettle   Author: pentaho   File: ConnectionPoolUtilIntegrationIT.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  driver = mock( Driver.class, RETURNS_MOCKS );
  DriverManager.registerDriver( driver );

  logChannelInterface = mock( LogChannelInterface.class, RETURNS_MOCKS );
  dsProps = new Properties();
  dsProps.setProperty( ConnectionPoolUtil.DEFAULT_AUTO_COMMIT, "true" );
  dsProps.setProperty( ConnectionPoolUtil.DEFAULT_READ_ONLY, "true" );
  dsProps.setProperty( ConnectionPoolUtil.DEFAULT_TRANSACTION_ISOLATION, "1" );
  dsProps.setProperty( ConnectionPoolUtil.DEFAULT_CATALOG, "" );
  dsProps.setProperty( ConnectionPoolUtil.MAX_IDLE, "30" );
  dsProps.setProperty( ConnectionPoolUtil.MIN_IDLE, "3" );
  dsProps.setProperty( ConnectionPoolUtil.MAX_WAIT, String.valueOf( MAX_WAIT_TIME ) ); // tested
  dsProps.setProperty( ConnectionPoolUtil.VALIDATION_QUERY, VALIDATION_QUERY );
  dsProps.setProperty( ConnectionPoolUtil.TEST_ON_BORROW, "true" );
  dsProps.setProperty( ConnectionPoolUtil.TEST_ON_RETURN, "true" );
  dsProps.setProperty( ConnectionPoolUtil.TEST_WHILE_IDLE, "true" );
  dsProps.setProperty( ConnectionPoolUtil.TIME_BETWEEN_EVICTION_RUNS_MILLIS, "300000" );
  dsProps.setProperty( ConnectionPoolUtil.POOL_PREPARED_STATEMENTS, "true" ); // tested
  dsProps.setProperty( ConnectionPoolUtil.MAX_OPEN_PREPARED_STATEMENTS, "2" ); // tested
  dsProps.setProperty( ConnectionPoolUtil.ACCESS_TO_UNDERLYING_CONNECTION_ALLOWED, "true" ); // tested
  dsProps.setProperty( ConnectionPoolUtil.REMOVE_ABANDONED, "false" );
  dsProps.setProperty( ConnectionPoolUtil.REMOVE_ABANDONED_TIMEOUT, "1000" );
  dsProps.setProperty( ConnectionPoolUtil.LOG_ABANDONED, "false" );
}
 
Example #17
Source Project: NutzCodematic   Author: Wizzercn   File: DBConnectionManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * ���غ�ע������JDBC��������
 * * * @param progs ���ӳ�����
 */
private void loadDrivers(Properties Props)
{
	String driverClasses=Props.getProperty("driver");
	StringTokenizer st=new StringTokenizer(driverClasses);
	while(st.hasMoreElements())
	{
		String driverClassName=st.nextToken().trim();
		try
		{
               Driver Driver =(Driver)	Class.forName(driverClassName).newInstance();
               DriverManager.registerDriver(Driver);
               drivers.addElement(Driver);
			log("�ɹ�ע��JDBC��������"+driverClassName);
		}
		catch(Exception e)
		{
			log("�޷�ע��JDBC��������"+driverClassName+",����"+e);
		}
	}

}
 
Example #18
Source Project: spliceengine   Author: splicemachine   File: Wrapper41Driver.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
public Driver   getWrappedObject() throws SQLException
{
    if ( _embedded != null ) { return _embedded; }
    else if ( _driver40 != null ) { return _driver40; }
    else if ( _netclient != null ) { return _netclient; }
    else { throw nothingWrapped( null ); }
}
 
Example #19
Source Project: presto   Author: prestosql   File: DriverConnectionFactory.java    License: Apache License 2.0 5 votes vote down vote up
public DriverConnectionFactory(Driver driver, BaseJdbcConfig config, CredentialProvider credentialProvider)
{
    this(driver,
            config.getConnectionUrl(),
            new Properties(),
            credentialProvider);
}
 
Example #20
Source Project: lams   Author: lamsfoundation   File: HsqlEmbeddedDatabaseConfigurer.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get the singleton {@link HsqlEmbeddedDatabaseConfigurer} instance.
 * @return the configurer
 * @throws ClassNotFoundException if HSQL is not on the classpath
 */
@SuppressWarnings("unchecked")
public static synchronized HsqlEmbeddedDatabaseConfigurer getInstance() throws ClassNotFoundException {
	if (instance == null) {
		instance = new HsqlEmbeddedDatabaseConfigurer( (Class<? extends Driver>)
				ClassUtils.forName("org.hsqldb.jdbcDriver", HsqlEmbeddedDatabaseConfigurer.class.getClassLoader()));
	}
	return instance;
}
 
Example #21
Source Project: gatf   Author: sumeetchhetri   File: CustomDriverManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Attempts to locate a driver that understands the given URL.
 * The <code>DriverManager</code> attempts to select an appropriate driver from
 * the set of registered JDBC drivers.
 *
 * @param url a database URL of the form
 *     <code>jdbc:<em>subprotocol</em>:<em>subname</em></code>
 * @return a <code>Driver</code> object representing a driver
 * that can connect to the given URL
 * @exception SQLException if a database access error occurs
 */
public static Driver getDriver(String url)
    throws SQLException {

    println("DriverManager.getDriver(\"" + url + "\")");

    // Gets the classloader of the code that called this method, may
    // be null.
    ClassLoader callerCL = Thread.currentThread().getContextClassLoader();

    // Walk through the loaded registeredDrivers attempting to locate someone
    // who understands the given URL.
    for (DriverInfo aDriver : registeredDrivers) {
        // If the caller does not have permission to load the driver then
        // skip it.
        if(isDriverAllowed(aDriver.driver, callerCL)) {
            try {
                if(aDriver.driver.acceptsURL(url)) {
                    // Success!
                    println("getDriver returning " + aDriver.driver.getClass().getName());
                return (aDriver.driver);
                }

            } catch(SQLException sqe) {
                // Drop through and try the next driver.
            }
        } else {
            println("    skipping: " + aDriver.driver.getClass().getName());
        }

    }

    println("getDriver: no suitable driver");
    throw new SQLException("No suitable driver", "08001");
}
 
Example #22
Source Project: dekaf   Author: JetBrains   File: ExasolIntermediateFacade.java    License: Apache License 2.0 5 votes vote down vote up
public ExasolIntermediateFacade(@NotNull final String connectionString,
                                @Nullable final Properties connectionProperties,
                                @NotNull final Driver driver,
                                final int connectionsLimit,
                                @NotNull final DBExceptionRecognizer exceptionRecognizer) {
  super(connectionString, connectionProperties, driver, connectionsLimit, exceptionRecognizer);
}
 
Example #23
Source Project: lams   Author: lamsfoundation   File: H2EmbeddedDatabaseConfigurer.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get the singleton {@code H2EmbeddedDatabaseConfigurer} instance.
 * @return the configurer
 * @throws ClassNotFoundException if H2 is not on the classpath
 */
@SuppressWarnings("unchecked")
public static synchronized H2EmbeddedDatabaseConfigurer getInstance() throws ClassNotFoundException {
	if (instance == null) {
		instance = new H2EmbeddedDatabaseConfigurer( (Class<? extends Driver>)
				ClassUtils.forName("org.h2.Driver", H2EmbeddedDatabaseConfigurer.class.getClassLoader()));
	}
	return instance;
}
 
Example #24
Source Project: dragonwell8_jdk   Author: alibaba   File: DriverManagerTests.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Register a driver and make sure you find it via its URL. Deregister the
 * driver and validate it is not longer registered
 *
 * @throws Exception
 */
@Test()
public void test15() throws Exception {
    DriverManager.registerDriver(new StubDriver());
    Driver d = DriverManager.getDriver(StubDriverURL);
    assertTrue(d != null);
    assertTrue(isDriverRegistered(d));
    DriverManager.deregisterDriver(d);
    assertFalse(isDriverRegistered(d));
}
 
Example #25
Source Project: reladomo   Author: goldmansachs   File: AbstractConnectionManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * sets the driver class name. This is used in conjunction with the JDBC connection string
 * @param driver the driver class name, for example "com.sybase.jdbc4.jdbc.SybDriver"
 */
public void setDriverClassName(String driver)
{
    try
    {
        this.driver = (Driver) Class.forName(driver).newInstance();
    }
    catch (Exception e)
    {
        throw new RuntimeException("Unable to load driver: " + driver, e);
    }
}
 
Example #26
Source Project: dremio-oss   Author: dremio   File: TracingProxyDriver.java    License: Apache License 2.0 5 votes vote down vote up
private void setProxyDriver( final Driver newProxyDriver,
                             final Driver proxiedDriver ) {
  // Note if different proxy than before.
  if ( null != this.proxyDriver && newProxyDriver != this.proxyDriver ) {
    reporter.setupMessage(
        "Note:  Multiple drivers proxied; Driver-level methods such as "
        + "getMajorVersion() will be routed to latest"
        + " (" + proxiedDriver + ")." );
  }
  this.proxyDriver = newProxyDriver;
}
 
Example #27
Source Project: pentaho-reporting   Author: pentaho   File: PooledDatasourceHelper.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
static Driver getDriver( IDatabaseDialect dialect, String driverClass, String url ) {
  if ( dialect instanceof IDriverLocator ) {
    return ( (IDriverLocator) dialect ).getDriver( url );
  } else {
    return ObjectUtilities.loadAndInstantiate( driverClass, PooledDatasourceHelper.class, Driver.class );
  }
}
 
Example #28
Source Project: Project   Author: GJXAIOU   File: MyTest26.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
        // 如果将 当前线程的上下文类加载器设置为 扩展类加载器 的话,ServiceLoader会用扩展类加载器加载
        // MySQL提供的 java.sql.Driver 的实现类,因为扩展类加载器不能加载到ClassPath里的jar,所以MySQL的实现类不会被加载
        //Thread.currentThread().setContextClassLoader(MyTest26.class.getClassLoader().getParent());

        // ServiceLoader 读取 mysql-connector-java-5.1.34.jar包下的 META-INF/services/java.sql.Driver
        // 而这个文件里的内容就是 com.mysql.jdbc.Driver
        //                      com.mysql.fabric.jdbc.FabricMySQLDriver
        // 这个文件的命名方式和内容,是 服务实现类根据的标准要求来实现的
        ServiceLoader<Driver> loader = ServiceLoader.load(Driver.class);
        Iterator<Driver> iterator = loader.iterator();

        while (iterator.hasNext()) {
            Driver driver = iterator.next();
            // 打印出 ServiceLoader加载的 实现了Driver接口的类信息,以及这个实现了Driver接口的类的类加载器
            System.out.println("driver: " + driver.getClass() + ", loader: " + driver.getClass().getClassLoader());
        }
        // 上面代码的运行结果
        /*
driver: class com.mysql.jdbc.Driver, loader: [email protected]
driver: class com.mysql.fabric.jdbc.FabricMySQLDriver, loader: [email protected]
         */

        System.out.println("当前线程上下文类加载器:" + Thread.currentThread().getContextClassLoader());
        System.out.println("ServiceLoader的类加载器:" + ServiceLoader.class.getClassLoader());
        // 上面代码的运行结果
        /*
当前线程上下文类加载器:[email protected]
ServiceLoader的类加载器:null
         */
        // ServiceLoader位于rt.jar,所以由启动器类加载器加载。默认的当前线程上下文类加载器是 AppClassLoader
    }
 
Example #29
Source Project: dekaf   Author: JetBrains   File: JdbcIntermediateFacade.java    License: Apache License 2.0 5 votes vote down vote up
public JdbcIntermediateFacade(@NotNull final String connectionString,
                              @Nullable final Properties connectionProperties,
                              @NotNull final Driver driver,
                              int connectionsLimit,
                              @NotNull final DBExceptionRecognizer exceptionRecognizer) {
  this(prepareDataSource(connectionString, connectionProperties, driver),
       connectionsLimit, true,
       exceptionRecognizer);
}
 
Example #30
Source Project: yawl   Author: yawlfoundation   File: YHttpServlet.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
private void deregisterDbDrivers() {
    Enumeration<Driver> drivers = DriverManager.getDrivers();
    while (drivers.hasMoreElements()) {
        Driver driver = drivers.nextElement();
        try {
            DriverManager.deregisterDriver(driver);
            _log.info("Deregistered JDBC driver: {}", driver);
        } catch (SQLException e) {
            _log.warn("Unable to deregister JDBC driver {}: {}", driver, e.getMessage());
        }
    }
}