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 File: CHouseIntermediateProvider.java From dekaf with Apache License 2.0 | 6 votes |
@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 #2
Source File: DataSourceUtils.java From clearpool with GNU General Public License v3.0 | 6 votes |
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 #3
Source File: DBConnectionManager.java From NutzCodematic with Apache License 2.0 | 6 votes |
/** * ���غ�ע������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 #4
Source File: TestPrestoDriver.java From presto with Apache License 2.0 | 6 votes |
@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 #5
Source File: ConnectionPoolUtilIntegrationIT.java From pentaho-kettle with Apache License 2.0 | 6 votes |
@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 #6
Source File: JdbcDataSourceFactory.java From obevo with Apache License 2.0 | 6 votes |
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 #7
Source File: StartupListener.java From dhis2-core with BSD 3-Clause "New" or "Revised" License | 6 votes |
@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 #8
Source File: DefaultPersistManager.java From onedev with MIT License | 6 votes |
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 #9
Source File: BaseHiveDialect.java From pentaho-metadata with GNU Lesser General Public License v2.1 | 6 votes |
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 #10
Source File: AbstractITest.java From ClickHouse-Native-JDBC with Apache License 2.0 | 6 votes |
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 #11
Source File: SimpleDriverDataSourceFactory.java From spring4-understanding with Apache License 2.0 | 6 votes |
@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 #12
Source File: ContainerContextClosedMySqlDriversHandlerListener.java From bamboobsc with Apache License 2.0 | 6 votes |
@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 #13
Source File: DatabaseConnector.java From cacheonix-core with GNU Lesser General Public License v2.1 | 6 votes |
/** * 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 File: BasicAuthJDBCTest.java From apiman with Apache License 2.0 | 6 votes |
/** * 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 #15
Source File: JdbcConnectionSourceTest.java From ormlite-jdbc with ISC License | 6 votes |
@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 #16
Source File: ConnectionFactory.java From query2report with GNU General Public License v3.0 | 6 votes |
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 #17
Source File: ConnectionFactory.java From mybatis-generator-core-fix with Apache License 2.0 | 6 votes |
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 #18
Source File: MyTest26.java From Project with Apache License 2.0 | 5 votes |
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: sun.misc.Launcher$AppClassLoader@135fbaa4 driver: class com.mysql.fabric.jdbc.FabricMySQLDriver, loader: sun.misc.Launcher$AppClassLoader@135fbaa4 */ System.out.println("当前线程上下文类加载器:" + Thread.currentThread().getContextClassLoader()); System.out.println("ServiceLoader的类加载器:" + ServiceLoader.class.getClassLoader()); // 上面代码的运行结果 /* 当前线程上下文类加载器:sun.misc.Launcher$AppClassLoader@135fbaa4 ServiceLoader的类加载器:null */ // ServiceLoader位于rt.jar,所以由启动器类加载器加载。默认的当前线程上下文类加载器是 AppClassLoader }
Example #19
Source File: RhnServletListener.java From uyuni with GNU General Public License v2.0 | 5 votes |
/** {@inheritDoc} */ public void contextDestroyed(ServletContextEvent sce) { saltReactor.stop(); logStop("Salt reactor"); stopMessaging(); logStop("Messaging"); stopHibernate(); logStop("Hibernate"); if (sce == null) { // this has been called from the testsuite, next steps would // break subsequent tests return; } // This manually deregisters JDBC driver, // which prevents Tomcat from complaining about memory leaks Enumeration<Driver> drivers = DriverManager.getDrivers(); while (drivers.hasMoreElements()) { Driver driver = drivers.nextElement(); try { DriverManager.deregisterDriver(driver); log.info("deregistering jdbc driver: " + driver); } catch (SQLException e) { log.warn("Error deregistering driver " + driver); } } // shutdown the logger to avoid ThreadDeath exception during // webapp reload. LogManager.shutdown(); }
Example #20
Source File: AbstractConnectionManager.java From reladomo with Apache License 2.0 | 5 votes |
/** * 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 #21
Source File: YHttpServlet.java From yawl with GNU Lesser General Public License v3.0 | 5 votes |
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()); } } }
Example #22
Source File: PostgresIntermediateFacade.java From dekaf with Apache License 2.0 | 5 votes |
public PostgresIntermediateFacade(@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 File: JDBCDataSourceUtil.java From birt with Eclipse Public License 1.0 | 5 votes |
/** * Load jdbc drivers * * @throws Exception */ private void loadJdbcDrivers() throws Exception { try { if ( "true".equals( System.getProperty( "DTETest.otherDB" ) ) ) { File driverHomeDir = getDriverHomeDir( ); URL[] urlList = getDriverFileURLs( driverHomeDir ); URLClassLoader urlClassLoader = new URLClassLoader( urlList, this.getClass( ).getClassLoader( ) ); Class c = urlClassLoader.loadClass( getDriverClassName( ) ); DriverExt driverExt = new DriverExt( (Driver) c.newInstance( ) ); DriverManager.registerDriver( driverExt ); } else { Class.forName( getDriverClassName( ) ); } } catch ( ClassNotFoundException e ) { System.out.println( "Due to licence issue, Driver lib for " + getDriverClassName( ) + " can not be " ); System.out.println( "checked into Eclipse CVS. Please manually download this driver lib and put it " ); System.out.println( "into test\\plugins\\org.eclipse.birt.report.data.oda.jdbc\\drivers directory." ); throw e; } }
Example #24
Source File: H2EmbeddedDatabaseConfigurer.java From effectivejava with Apache License 2.0 | 5 votes |
/** * 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 #25
Source File: DBCPServiceTest.java From nifi with Apache License 2.0 | 5 votes |
/** * NB!!!! Prerequisite: file should be present in /var/tmp/mariadb-java-client-1.1.7.jar Prerequisite: access to running MariaDb database server */ @Test @Ignore("Intended only for local testing, not automated testing") public void testURLClassLoaderGetConnection() 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); final Connection connection = DriverManager.getConnection("jdbc:mariadb://localhost:3306/testdb", "tester", "testerp"); assertNotNull(connection); connection.close(); DriverManager.deregisterDriver(shim); }
Example #26
Source File: MssqlIntermediateProvider.java From dekaf with Apache License 2.0 | 5 votes |
@NotNull @Override protected MssqlIntermediateFacade instantiateFacade(@NotNull final String connectionString, @Nullable final Properties connectionProperties, final int connectionsLimit, @NotNull final Driver driver) { return new MssqlIntermediateFacade(connectionString, connectionProperties, driver, connectionsLimit, MssqlExceptionRecognizer.INSTANCE); }
Example #27
Source File: DriverManagerTests.java From dragonwell8_jdk with GNU General Public License v2.0 | 5 votes |
/** * 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 #28
Source File: H2dbIntermediateProvider.java From dekaf with Apache License 2.0 | 5 votes |
@NotNull @Override protected H2dbIntermediateFacade instantiateFacade(@NotNull final String connectionString, @Nullable final Properties connectionProperties, final int connectionsLimit, @NotNull final Driver driver) { return new H2dbIntermediateFacade(connectionString, connectionProperties, driver, connectionsLimit, H2dbExceptionRecognizer.INSTANCE); }
Example #29
Source File: JdbcDrivers.java From dekaf with Apache License 2.0 | 5 votes |
@Nullable public static Driver findPreferredDriverFor(@NotNull final String connectionString) { final Collection<Driver> drivers = getPreferredDrivers(); for (Driver driver : drivers) { if (isDriverAcceptingConnectionString(driver, connectionString)) return driver; } return null; }
Example #30
Source File: ConnectionFactory.java From query2report with GNU General Public License v3.0 | 5 votes |
public static boolean testConnection(ConnectionParams params) throws Exception { boolean status = false; 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); if(driver.acceptsURL(url)){ Connection connection = driver.connect(url, props); connection.setAutoCommit(false); logger.info("Got new connection to DB " + url + " for user " + username); status=true; params.setIsConnectionSuccess(Boolean.toString(status)); connection.close(); }else{ logger.error("Driver "+params.getDriver()+" is not suitable for URL "+url); throw new RuntimeException("Driver "+params.getDriver()+" is not suitable for URL "+url); } }catch (Throwable e){ logger.error("Error getting connection to "+url+" for user "+username,e); throw e; } return status; }