下面列出了java.sql.DriverManager#registerDriver ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Before
public void setUp() throws SQLException {
DriverManager.registerDriver(new MockDriver());
// use our mock driver
datasource.setDriverClassName(MockDriver.class.getName());
datasource.setUrl(MockDriver.getUrlWithValidationOutcomes(ValidationOutcome.SUCCESS));
// Required to trigger validation query's execution
datasource.setInitialSize(1);
datasource.setMinIdle(1);
datasource.setMaxIdle(1);
datasource.setMaxActive(2);
// Validation interval is disabled by default to ensure validation occurs everytime
datasource.setValidationInterval(-1);
// No validation query by default
datasource.setValidationQuery(null);
}
/**
* Validate that a Connection object is returned when a valid URL is
* specified to getConnection
*
*/
@Test
public void test14() throws Exception {
DriverManager.registerDriver(new StubDriver());
assertTrue(
DriverManager.getConnection(StubDriverURL) != null);
assertTrue(DriverManager.getConnection(StubDriverURL,
"LuckyDog", "tennisanyone") != null);
Properties props = new Properties();
props.put("user", "LuckyDog");
props.put("password", "tennisanyone");
assertTrue(
DriverManager.getConnection(StubDriverURL,
props) != null);
}
@Test
public void testRetrieveFromDriverManager() throws Exception {
// we're not (directly) using a Mockito based mock class here because it won't have a consistent class name
// that will work with DriverManager's class bindings
MockDriver mockDriver = new MockDriver(connection);
DriverManager.registerDriver(mockDriver);
try {
props.put(JdbcDataSource.DRIVER, MockDriver.class.getName());
props.put(JdbcDataSource.URL, MockDriver.MY_JDBC_URL);
props.put("holdability", "HOLD_CURSORS_OVER_COMMIT");
Connection conn = jdbcDataSource.createConnectionFactory(context, props).call();
verify(connection).setAutoCommit(false);
verify(connection).setHoldability(1);
assertSame("connection", conn, connection);
} catch(Exception e) {
throw e;
} finally {
DriverManager.deregisterDriver(mockDriver);
}
}
private synchronized void initializeDriver() throws SQLException {
//这里便是大家熟悉的初学JDBC时的那几句话了 Class.forName newInstance()
if (!registeredDrivers.containsKey(driver)) {
Class<?> driverType;
try {
if (driverClassLoader != null) {
driverType = Class.forName(driver, true, driverClassLoader);
} else {
driverType = Resources.classForName(driver);
}
// DriverManager requires the driver to be loaded via the system ClassLoader.
// http://www.kfu.com/~nsayer/Java/dyn-jdbc.html
Driver driverInstance = (Driver)driverType.newInstance();
DriverManager.registerDriver(new DriverProxy(driverInstance));
registeredDrivers.put(driver, driverInstance);
} catch (Exception e) {
throw new SQLException("Error setting driver on UnpooledDataSource. Cause: " + e);
}
}
}
/**
* NB!!!! Prerequisite: file should be present in /var/tmp/mariadb-java-client-1.1.7.jar
*/
@Test
@Ignore("Intended only for local testing, not automated testing")
public void testURLClassLoader() throws ClassNotFoundException, MalformedURLException, SQLException, InstantiationException, IllegalAccessException {
final URL url = new URL("file:///var/tmp/mariadb-java-client-1.1.7.jar");
final URL[] urls = new URL[] { url };
final ClassLoader parent = Thread.currentThread().getContextClassLoader();
final URLClassLoader ucl = new URLClassLoader(urls, parent);
final Class<?> clazz = Class.forName("org.mariadb.jdbc.Driver", true, ucl);
assertNotNull(clazz);
final Driver driver = (Driver) clazz.newInstance();
final Driver shim = new DriverShim(driver);
DriverManager.registerDriver(shim);
final Driver driver2 = DriverManager.getDriver("jdbc:mariadb://localhost:3306/testdb");
assertNotNull(driver2);
}
/**
* Validate that a non-null Driver is returned by getDriver when a valid URL
* is specified
*/
@Test
public void test12() throws Exception {
DriverManager.registerDriver(new StubDriver());
assertTrue(DriverManager.getDriver(StubDriverURL) != null);
}
/** Test.
* @throws SQLException e */
@Before
public void setUp() throws SQLException {
Utils.initialize();
Utils.setProperty(Parameter.SYSTEM_ACTIONS_ENABLED, Boolean.TRUE.toString());
driver = new JdbcDriver();
DriverManager.registerDriver(driver);
jdbcWrapper = JdbcWrapper.SINGLETON;
}
@BeforeClass
public static synchronized void doSetup() throws Exception {
Map<String, String> props = Maps.newHashMapWithExpectedSize(3);
// Disable system task handling
props.put(QueryServices.TASK_HANDLING_INITIAL_DELAY_MS_ATTRIB, Long.toString(Long.MAX_VALUE));
// Phoenix Global client metrics are enabled by default
// Enable request metric collection at the driver level
props.put(QueryServices.COLLECT_REQUEST_LEVEL_METRICS, String.valueOf(true));
// disable renewing leases as this will force spooling to happen.
props.put(QueryServices.RENEW_LEASE_ENABLED, String.valueOf(false));
setUpTestDriver(new ReadOnlyProps(props.entrySet().iterator()));
// need the non-test driver for some tests that check number of hconnections, etc.
DriverManager.registerDriver(PhoenixDriver.INSTANCE);
}
/**
* 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));
}
/**
* Register the driver against {@link DriverManager}. This is done automatically when the class is
* loaded. Dropping the driver from DriverManager's list is possible using {@link #deregister()}
* method.
*
* @throws IllegalStateException if the driver is already registered
* @throws SQLException if registering the driver fails
*/
public static void register() throws SQLException {
if (isRegistered()) {
throw new IllegalStateException(
"Driver is already registered. It can only be registered once.");
}
CloudSpannerDriver registeredDriver = new CloudSpannerDriver();
DriverManager.registerDriver(registeredDriver);
CloudSpannerDriver.registeredDriver = registeredDriver;
}
/**
* Registers this driver with the driver manager.
*/
protected void register() {
try {
DriverManager.registerDriver(this);
} catch (SQLException e) {
System.out.println(
"Error occurred while registering JDBC driver "
+ this + ": " + e.toString());
}
}
/**
* 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;
}
/**
* Validate that NullPointerException is thrown when null is passed to
* registerDriver
*/
@Test(expectedExceptions = NullPointerException.class)
public void test2() throws Exception {
Driver d = null;
DriverManager.registerDriver(d, null);
}
@Before
public void registerDriver() throws Exception {
Driver driver = driverClass.getDriver().newInstance();
DriverManager.registerDriver(driver);
}
/**
* Validate that NullPointerException is thrown when null is passed to
* registerDriver
*/
@Test(expectedExceptions = NullPointerException.class)
public void test1() throws Exception {
Driver d = null;
DriverManager.registerDriver(d);
}
@BeforeClass
public static void setUpBeforeClass() throws Exception {
DriverManager.registerDriver( new org.h2.Driver( ) );
sm = StorageManagerFactory.getInstance( "org.hsqldb.jdbcDriver","sa","" ,"jdbc:hsqldb:mem:.", Main.DEFAULT_MAX_DB_CONNECTIONS);
}
@BeforeClass
public static void setUpBeforeClass() throws Exception {
DriverManager.registerDriver( new org.h2.Driver( ) );
sm = StorageManagerFactory.getInstance( "org.hsqldb.jdbcDriver","sa","" ,"jdbc:hsqldb:mem:.", Main.DEFAULT_MAX_DB_CONNECTIONS);
}
/**
* 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);
}
/**
* 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);
}
/**
* 获取数据库连接
* @return
*/
private static Connection getConnection() throws Exception{
Install install = getDatabaseParameter();
//linux下5.7必须加这句,不然会报错java.sql.SQLException: No suitable driver found for
DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());//注册驱动
return DriverManager.getConnection(install.getDatabaseURL().trim(), install.getDatabaseUser().trim(), install.getDatabasePassword().trim());
}