下面列出了怎么用java.sql.Driver的API类实例代码及写法,或者点击链接到github查看源代码。
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);
}
@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);
}
}
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;
}
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;
}
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;
}
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();
}
}
@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;
}
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;
}
}
@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);
}
}
/**
* 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;
}
@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();
}
@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);
}
};
}
/**
* 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);
}
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);
}
}
@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() );
}
}
}
@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" );
}
/**
* ���غ�ע������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);
}
}
}
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 ); }
}
public DriverConnectionFactory(Driver driver, BaseJdbcConfig config, CredentialProvider credentialProvider)
{
this(driver,
config.getConnectionUrl(),
new Properties(),
credentialProvider);
}
/**
* 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;
}
/**
* 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");
}
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);
}
/**
* 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;
}
/**
* 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));
}
/**
* 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);
}
}
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;
}
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 );
}
}
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
}
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);
}
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());
}
}
}