java.sql.DriverManager#getDriver ( )源码实例Demo

下面列出了java.sql.DriverManager#getDriver ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: spliceengine   文件: DriverTest.java
/**
 * Do java.sql.Driver.connect(String url, Properties info call)
 *
 * @param expectUrlEqualsGetUrl boolean indicating embedded would
 *                  expect the url passed in to equal metadata.getURL()
 * @param url       url to pass to Driver.connect()
 * @param info      properties to pass to Driver.Connect()
 *
 * @throws SQLException on error.
 */
private static void assertConnect(
        boolean expectUrlEqualsGetUrl, String url, Properties info)
        throws SQLException
{
    Driver driver = DriverManager.getDriver(url);

    Connection conn = driver.connect(url, info);
    assertNotNull(conn);

    if (expectUrlEqualsGetUrl)
        assertEquals(url, conn.getMetaData().getURL());
    else
        assertNotSame(url, conn.getMetaData().getURL());
    ResultSet rs =
            conn.createStatement().executeQuery("VALUES(CURRENT SCHEMA)");
    rs.next();
    assertEquals(
            rs.getString(1), conn.getMetaData().getUserName().toUpperCase());
    rs.close();
    conn.close();
    return;
}
 
源代码2 项目: spliceengine   文件: Driver40UnbootedTest.java
/**
 * <p>
 * This entry point is used to run a separate java process in order to verify
 * that the correct exception is being raised by getParentLogger() when the
 * engine hasn't been booted yet.
 * </p>
 */
public  static  void    main( String[] args )  throws Exception
{
    Driver  embeddedDriver = DriverManager.getDriver( "jdbc:splice:" );
    Wrapper41Driver embeddedWrapper = new Wrapper41Driver( embeddedDriver );

    String  statusMessage = SUCCESS;
    
    try {
        embeddedWrapper.getParentLogger();
        statusMessage = "getParentLogger() unexpectedly succeeded";
    }
    catch (Exception se)
    {
        if ( !( se instanceof SQLFeatureNotSupportedException ) )
        {
            statusMessage = "Exception was not a SQLFeatureNotSupportedException. It was a " + se.getClass().getName();
        }
    }

    System.out.print( statusMessage );
}
 
源代码3 项目: commons-dbcp   文件: PoolingDriverExample.java
public static void printDriverStats() throws Exception {
    PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:");
    ObjectPool<? extends Connection> connectionPool = driver.getConnectionPool("example");

    System.out.println("NumActive: " + connectionPool.getNumActive());
    System.out.println("NumIdle: " + connectionPool.getNumIdle());
}
 
源代码4 项目: javasimon   文件: Driver.java
/**
 * Tries to determine driver class, instantiate it and register if already not registered.
 * For more detail look at {@link Driver} class javadoc.
 *
 * @param configuration instance of url object that represents url
 * @param info parameters from {@link #connect(String, java.util.Properties)} method
 * @return instance of real driver
 * @throws java.sql.SQLException if real driver can't be determined or is not registerd
 */
private java.sql.Driver getRealDriver(SimonConnectionConfiguration configuration, Properties info) throws SQLException {
	java.sql.Driver drv = null;
	try {
		drv = DriverManager.getDriver(configuration.getRealUrl());
	} catch (SQLException e) {
		// nothing, not an error
	}

	if (drv == null && info != null && info.keySet().contains(SimonConnectionConfiguration.REAL_DRIVER)) {
		drv = registerDriver(info.getProperty(SimonConnectionConfiguration.REAL_DRIVER));
	}

	if (drv == null && configuration.getRealDriver() != null) {
		drv = registerDriver(configuration.getRealDriver());
	}

	if (drv == null) {
		if (configuration.getRealDriver() != null) {
			drv = registerDriver(configuration.getRealDriver());
		}
	}

	if (drv == null) {
		throw new SQLException("Real driver is not registered and can't determine real driver class name for registration.");
	}
	return drv;
}
 
源代码5 项目: spliceengine   文件: DriverTest.java
/**
 * Load the driver and check java.sql.Driver.jdbcCompliant() and
 * driver.get*Version
 * @throws Exception
 */
public void testDriverCompliantVersion() throws Exception
{
    String dbName = TestConfiguration.getCurrent().getDefaultDatabaseName();
    String url = TestConfiguration.getCurrent().getJDBCUrl(dbName);

    loadDriver();
    String defaultdburl = url + ";create=true";

    // Test that we loaded the right driver by making a connection
    Driver driver = DriverManager.getDriver(defaultdburl);
    Properties props = new Properties();
    props.put("user", "testuser");
    props.put("password", "testpass");
    Connection conn = DriverManager.getConnection(defaultdburl, props);
    // Driver should be jdbc compliant.
    assertTrue(driver.jdbcCompliant());

    // compare driver.get*Version() with DatabaseMetadata.getDriver*Version.
    DatabaseMetaData dbmd = conn.getMetaData();

    assertEquals(dbmd.getDriverMajorVersion(), driver.getMajorVersion());
    assertEquals(dbmd.getDriverMinorVersion(), driver.getMinorVersion());

    // test that the driver is one of the special 40 versions if we are running
    // on Java 6 or higher
    println( "Driver is a " + driver.getClass().getName() );
    assertEquals( JDBC.vmSupportsJDBC4(), driver.getClass().getName().endsWith( "40" ) );

    conn.close();
}
 
源代码6 项目: TencentKona-8   文件: DriverManagerTests.java
/**
 * 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));
}
 
源代码7 项目: openjdk-jdk8u   文件: DriverManagerTests.java
/**
 * Validate that DriverAction.release is called when a driver is registered
 * via registerDriver(Driver, DriverAction)
 *
 * @throws Exception
 */
@Test
public void test16() throws Exception {
    File file = new File(util.StubDriverDA.DriverActionCalled);
    file.delete();
    assertFalse(file.exists());
    Driver d = null;
    Class.forName("util.StubDriverDA");
    d = DriverManager.getDriver(StubDriverDAURL);
    DriverManager.deregisterDriver(d);
    assertFalse(isDriverRegistered(d), "Driver is registered");
    assertTrue(file.exists());
}
 
源代码8 项目: jdk8u-jdk   文件: DriverManagerTests.java
/**
 * 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));
}
 
源代码9 项目: gemfirexd-oss   文件: SlaveDatabase.java
/**
     * Used to shutdown this database. 
     *
     * If an error occurs as part of the database boot process, we
     * hand the exception that caused boot to fail to the client
     * thread. The client thread will in turn shut down this database.
     *
     * If an error occurs at a later stage than during boot, we shut
     * down the database by setting up a connection with the shutdown
     * attribute. The internal connection is required because database
     * shutdown requires EmbedConnection to do cleanup.
     *
     * @param shutdownCause the reason why the database needs to be
     * shutdown
     */
    private void handleShutdown(StandardException shutdownCause) {
        if (inBoot) {
            bootException = shutdownCause;
            return;
        } 
        try {
            shutdownInitiated = true;
            String driverName = 
                "com.pivotal.gemfirexd.jdbc.EmbeddedDriver";

            Class.forName(driverName).newInstance();

            Driver embedDriver = 
                DriverManager.getDriver(com.pivotal.gemfirexd.Attribute.PROTOCOL);

// GemStone changes BEGIN
            String conStr = com.pivotal.gemfirexd.Attribute.PROTOCOL + ";" +
            /* String conStr = "jdbc:derby:"+dbname+";"+ */
// GemStone changes END
                Attribute.REPLICATION_INTERNAL_SHUTDOWN_SLAVE+
                "=true";

            embedDriver.connect(conStr, (Properties) null);
        } catch (Exception e) {
            // Todo: report error to gemfirexd.log if exception is not
            // SQLState.SHUTDOWN_DATABASE
        }
    }
 
源代码10 项目: phoenix   文件: BaseTest.java
/**
 * Create a {@link PhoenixTestDriver} and register it.
 * @return an initialized and registered {@link PhoenixTestDriver} 
 */
protected static PhoenixTestDriver initAndRegisterDriver(String url, ReadOnlyProps props) throws Exception {
    PhoenixTestDriver newDriver = new PhoenixTestDriver(props);
    DriverManager.registerDriver(newDriver);
    Driver oldDriver = DriverManager.getDriver(url); 
    if (oldDriver != newDriver) {
        destroyDriver(oldDriver);
    }
    Connection conn = newDriver.connect(url, PropertiesUtil.deepCopy(TEST_PROPERTIES));
    conn.close();
    return newDriver;
}
 
源代码11 项目: jdk8u60   文件: DriverManagerTests.java
/**
 * Validate that DriverAction.release is called when a driver is registered
 * via registerDriver(Driver, DriverAction)
 *
 * @throws Exception
 */
@Test
public void test16() throws Exception {
    File file = new File(util.StubDriverDA.DriverActionCalled);
    file.delete();
    assertFalse(file.exists());
    Driver d = null;
    Class.forName("util.StubDriverDA");
    d = DriverManager.getDriver(StubDriverDAURL);
    DriverManager.deregisterDriver(d);
    assertFalse(isDriverRegistered(d), "Driver is registered");
    assertTrue(file.exists());
}
 
源代码12 项目: snowflake-jdbc   文件: SnowflakeDriverIT.java
@Test
public void testGetPropertyInfo() throws SQLException
{
  // Test with blank URL and no properties. ServerURL is needed.
  String url = "";
  Properties props = new Properties();
  Driver driver = DriverManager.getDriver("jdbc:snowflake://snowflake.reg.local:8082");
  DriverPropertyInfo[] info = driver.getPropertyInfo(url, props);
  assertEquals(1, info.length);
  assertEquals("serverURL", info[0].name);
  assertEquals("server URL in form of <protocol>://<host or domain>:<port number>/<path of resource>",
               info[0].description);

  // Test with URL that requires username and password.
  url = "jdbc:snowflake://snowflake.reg.local:8082";
  info = driver.getPropertyInfo(url, props);
  assertEquals(2, info.length);
  assertEquals("user", info[0].name);
  assertEquals("username for account",
               info[0].description);
  assertEquals("password", info[1].name);
  assertEquals("password for account", info[1].description);

  // Add username and try again; get password requirement back
  props.put("user", "snowman");
  props.put("password", "test");
  info = driver.getPropertyInfo(url, props);
  assertEquals(0, info.length);

  props.put("useProxy", "true");
  info = driver.getPropertyInfo(url, props);
  assertEquals(2, info.length);
  assertEquals("proxyHost", info[0].name);
  assertEquals("proxy host name", info[0].description);
  assertEquals("proxyPort", info[1].name);
  assertEquals("proxy port; should be an integer", info[1].description);

  props.put("proxyHost", "dummyHost");
  props.put("proxyPort", "dummyPort");
  info = driver.getPropertyInfo(url, props);
  assertEquals(0, info.length);

  // invalid URL still throws SQLException
  try
  {
    url = "snowflake.reg.local:8082";
    driver.getPropertyInfo(url, props);
  }
  catch (SQLException e)
  {
    assertEquals((int) ErrorCode.INVALID_CONNECT_STRING.getMessageCode(), e.getErrorCode());
  }
}
 
源代码13 项目: spanner-jdbc   文件: CloudSpannerDriverTest.java
private static Driver getDriver() throws SQLException {
  return DriverManager.getDriver("jdbc:cloudspanner://localhost");
}
 
源代码14 项目: hottub   文件: DriverManagerTests.java
/**
 * Validate that SQLException is thrown when there is no Driver to service
 * the URL
 */
@Test(expectedExceptions = SQLException.class)
public void test10() throws Exception {
    DriverManager.getDriver(InvalidURL);
}
 
源代码15 项目: gemfirexd-oss   文件: DriverTest.java
/**
 * Check that drivers accept the correct urls and reject those for other supported drivers.
 *
 * @throws SQLException, Exception
 */
public void testAcceptsURL() throws SQLException, Exception {
    String dbName = TestConfiguration.getCurrent().getDefaultDatabaseName();
    String orgurl = TestConfiguration.getCurrent().getJDBCUrl(dbName);

    loadDriver();
    String defaultdburl = orgurl + ";create=true";

    // Test that we loaded the right driver by making a connection
    Driver driver = DriverManager.getDriver(defaultdburl);

    int  frameworkOffset;
    int EMBEDDED_OFFSET = 0;
    int DERBYNETCLIENT_OFFSET = 1;
    if (usingDerbyNetClient())
        frameworkOffset = DERBYNETCLIENT_OFFSET;
    else // assume (usingEmbedded())
        frameworkOffset = EMBEDDED_OFFSET;

    // URLS to check.  New urls need to also be added to the acceptsUrl table
    //GemStone changes BEGIN
    //String EMBEDDED_URL = "jdbc:derby:";
    String EMBEDDED_URL = "jdbc:gemfirexd:";
    // GemStone changes END
    String INVALID_URL = "jdbc:db2j:";
    String hostName = TestConfiguration.getCurrent().getHostName();
    int port = TestConfiguration.getCurrent().getPort();
    String CLIENT_URL =
        "jdbc:derby://"+hostName+":"+port+"/"+dbName+";create=true";

    String[] urls = new String[]
    {
        EMBEDDED_URL,
        CLIENT_URL,
        INVALID_URL,
    };

    // Table that shows whether tested urls should return true for
    // acceptsURL under the given framework
    // The acceptsURLTable uses  the frameworkOffset column int he table
    // to check for valid results for each framework
    boolean[][] acceptsURLTable = new boolean[][]
    {
    // Framework/url      EMBEDDED     DERBYNETCLIENT
    /* EMBEDDED_URL*/  {   true      ,  false        },
    /* CLIENT_URL  */  {   false     ,  true         },
    /* INVALID_URL */  {   false     ,  false        }
    };

    for (int u = 0; u < urls.length;u++)
    {
        String url = urls[u];
        boolean expectedAcceptance = acceptsURLTable[u][frameworkOffset];
        boolean actualAcceptance = driver.acceptsURL(url);
        assertEquals(expectedAcceptance, actualAcceptance);
    }
}
 
源代码16 项目: gemfirexd-oss   文件: NetworkServerControlImpl.java
/** 
	 * Load Derby and save driver for future use.
	 * We can't call Driver Manager when the client connects, 
	 * because they might be holding the DriverManager lock.
	 *
	 * 
	 */

	


// GemStone changes BEGIN
        @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="DM_GC")
// GemStone changes END
	protected void startNetworkServer() throws Exception
	{

		// we start the Derby server here.
		boolean restartCheck = this.restartFlag;
		synchronized (serverStartSync) {

			if (restartCheck == this.restartFlag) {
			// then we can go ahead and restart the server (odds
			// that some else has just done so are very slim (but not
			// impossible--however, even if it does happen, things
			// should still work correctly, just not as efficiently...))

				try {
	
					if (cleanupOnStart) {
					// we're restarting the server (probably after a shutdown
					// exception), so we need to clean up first.

						// Close and remove sessions on runQueue.
						synchronized (runQueue) {
							for (int i = 0; i < runQueue.size(); i++) {
								Session s = (Session) runQueue.get(i);
								s.close();
								removeFromSessionTable(s.getConnNum());
							}
							runQueue.clear();
						}

						// DERBY-1326: There could be active threads that
						// contain old/invalid sessions. These sessions won't
						// be cleaned up until there is some activity on
						// them. We could optimize this by going through
						// sessionTable and closing the sessions' socket
						// streams.

						// Unload driver, then restart the server.
						cloudscapeDriver = null;	// so it gets collected.
						System.gc();
					}

					// start the server.
					Class.forName(CLOUDSCAPE_DRIVER).newInstance();
					cloudscapeDriver = DriverManager.getDriver(com.pivotal.gemfirexd.Attribute.PROTOCOL);

				}
				catch (Exception e) {
                    this.consoleExceptionPrintTrace(e);
					consolePropertyMessage("DRDA_LoadException.S", e.getMessage());
				}
				cleanupOnStart = true;
				this.restartFlag = !this.restartFlag;
			}
			// else, multiple threads hit this synchronize block at the same
			// time, but one of them already executed it--so all others just
			// return and do nothing (no need to restart the server multiple
			// times in a row).
		}
	}
 
源代码17 项目: openjdk-jdk8u-backup   文件: DriverManagerTests.java
/**
 * Validate that SQLException is thrown when the URL is not valid for any of
 * the registered drivers
 */
@Test(expectedExceptions = SQLException.class)
public void test13() throws Exception {
    DriverManager.registerDriver(new StubDriver());
    DriverManager.getDriver(InvalidURL);
}
 
源代码18 项目: beakerx   文件: BxDriverManager.java
public static Driver getDriver(String url) throws SQLException {
  return DriverManager.getDriver(url);
}
 
源代码19 项目: dekaf   文件: SybaseInterServiceProviderTest.java
@Test
public void driverIsLoaded() throws SQLException {
  final Driver driver = DriverManager.getDriver(SYBASE_JTDS_CONNECTION_STRING_EXAMPLE);
  assertThat(driver).isNotNull();
}
 
源代码20 项目: gemfirexd-oss   文件: DriverTest.java
/**
 * Tests client URLs to see connection is successful or the correct exception is thrown.
 */
public void testClientURL() throws SQLException {
    if (!usingDerbyNetClient())
        return;

    String dbName = TestConfiguration.getCurrent().getDefaultDatabaseName();
    String protocol =
        TestConfiguration.getCurrent().getJDBCClient().getUrlBase();
    if (usingDerbyNetClient())
        protocol = protocol + TestConfiguration.getCurrent().getHostName()
        + ":" + TestConfiguration.getCurrent().getPort() + "/";

    Properties info = null;     //test with null Properties object

    String CLIENT_CREATE_URL_WITH_COLON1 =
        protocol + dbName + ":create=true";
    //String CLIENT_CREATE_URL_WITH_COLON2 = protocol + DERBY_SYSTEM_HOME +
    //   File.separator + dbName + ":create=true";
    // String CLIENT_CREATE_URL_WITH_DOUBLE_QUOTES1 =
    //     protocol + "\"" + dbName + "\";create=true";
    // String CLIENT_CREATE_URL_WITH_DOUBLE_QUOTES2 = protocol + "\"" +
    //     DERBY_SYSTEM_HOME + File.separator + dbName + "\";create=true";
    // String CLIENT_CREATE_URL_WITH_SINGLE_QUOTES1 = protocol + "'" +
    //     DERBY_SYSTEM_HOME + File.separator + dbName + "';create=true";
    String CLIENT_CREATE_URL_WITH_SINGLE_QUOTES2 =
        protocol + "'" + dbName + "';create=true";

    String CLIENT_SHUT_URL_WITH_SINGLE_QUOTES2 =
        protocol + "'" + dbName + "';shutdown=true";

    //Client URLS
    String[] clientCreateUrls = new String[]
    {
        CLIENT_CREATE_URL_WITH_COLON1,
        //CLIENT_URL_WITH_COLON2,
        //CLIENT_URL_WITH_DOUBLE_QUOTES1,
        //CLIENT_URL_WITH_DOUBLE_QUOTES2,
        //CLIENT_URL_WITH_SINGLE_QUOTES1,
        CLIENT_CREATE_URL_WITH_SINGLE_QUOTES2
    };

    for (int i = 0; i < clientCreateUrls.length;i++)
    {
        String url = clientCreateUrls[i];
        try{
            if (url.equals(CLIENT_CREATE_URL_WITH_COLON1))
            {
                Driver driver = DriverManager.getDriver(url);
                assertNull(driver.connect(url,info));
            }
            else
                assertConnect(true, url, info);
        }
        catch(SQLException se){
            fail ("did not expect an exception");
        }
    }
    // shutdown the databases, which should get rid of all open connections
    // currently, there's only the one; otherwise, this could be done in
    // a loop.
    shutdownDB(
        CLIENT_SHUT_URL_WITH_SINGLE_QUOTES2 + ";shutdown=true", null);
}