/** * 装载和注册所有JDBC 驱动程序 * * @param props 属性 */ private void loadDrivers(Vector driverBeans) { logger.debug("----------------------->"); Iterator iterator = driverBeans.iterator(); while (iterator.hasNext()) { DSConfigBean dsConfigBean = (DSConfigBean)iterator.next(); try { if (dsConfigBean.getDriver() != null && !"".equals(dsConfigBean.getDriver())){ Driver driver = (Driver) Class.forName(dsConfigBean.getDriver()) .newInstance(); DriverManager.registerDriver(driver); drivers.addElement(driver); logger.debug("成功注册JDBC 驱动程序" + dsConfigBean.getDriver()); } } catch (Exception e) { logger.error("注册驱动程序出错,",e); } } }
@Override public Class<? extends Driver> getDriverClass(DbEnvironment env) { if (env.getDbServer() != null) { try { if (isSqlAnywhereDriverAvailable()) { return (Class<? extends Driver>) Class.forName(SQLANYWHERE_DRIVER_CLASS_NAME); } else if (isIanywhereDriverAvailable()) { return (Class<? extends Driver>) Class.forName(IANYWHERE_DRIVER_CLASS_NAME); } } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } return super.getDriverClass(env); }
public Connection getConnection() throws SQLException { Driver driver = getDriver(); Properties props = new Properties(); if (stringHasValue(userId)) { props.setProperty("user", userId); //$NON-NLS-1$ } if (stringHasValue(password)) { props.setProperty("password", password); //$NON-NLS-1$ } props.putAll(otherProperties); Connection conn = driver.connect(connectionURL, props); if (conn == null) { throw new SQLException(getString("RuntimeError.7")); //$NON-NLS-1$ } return conn; }
@Test public void driverPropertyInfoWithoutValues() throws SQLException { Driver driver = getDriver(); DriverPropertyInfo[] properties = driver.getPropertyInfo("jdbc:cloudspanner://localhost", null); assertEquals(12, properties.length); for (DriverPropertyInfo property : properties) { if (property.name.equals("AllowExtendedMode") || property.name.equals("AsyncDdlOperations") || property.name.equals("AutoBatchDdlOperations")) assertEquals("false", property.value); else if (property.name.equals("ReportDefaultSchemaAsNull")) assertEquals("true", property.value); else assertNull(property.value); } }
private boolean isDriverClass(URLClassLoader jarloader, String className) { Class<?> clazz; try { clazz = jarloader.loadClass(className); } catch ( Throwable t ) { LOGGER.log(Level.FINE, null, t); LOGGER.log(Level.INFO, "Got an exception trying to load class " + className + " during search for JDBC drivers in " + " driver jar(s): " + t.getClass().getName() + ": " + t.getMessage() + ". Skipping this class..."); // NOI18N return false; } if ( Driver.class.isAssignableFrom(clazz) ) { return true; } return false; }
public Connection getConnection(ISqlConfig config) { if(conn == null){ IConnectionParam param = config.getConnectionParam(); try { Driver d = (Driver)Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver").newInstance(); if(param.getUsername().trim().length()>0){ // USERNAME & PASSWORD is configured, let's use it for connection conn = DriverManager.getConnection("jdbc:odbc:"+param.getURL(),param.getUsername(),param.getPassword()); } else { conn = DriverManager.getConnection("jdbc:odbc:"+param.getURL()); } } catch (Exception e) { throw new RuntimeException(e); } } return conn; }
/** * Get the driver for a JDBCDriver. It only tries to load it using Class.forName() - * there is no URL to work with */ public Driver getDriver(JDBCDriver jdbcDriver) throws SQLException { ClassLoader l = getClassLoader(jdbcDriver); Object driver; try { driver = Class.forName(jdbcDriver.getClassName(), true, l).newInstance(); } catch (Exception e) { SQLException sqlex = createDriverNotFoundException(); sqlex.initCause(e); throw sqlex; } if (driver instanceof Driver) { return (Driver) driver; } else { throw new SQLException(driver.getClass().getName() + " is not a driver"); //NOI18N } }
public static Connection createConnection(Properties p,File[] f) throws Exception{ String driver_name=p.getProperty(DRIVER_CLASS_NAME); String url=p.getProperty(URL); String user=p.getProperty(USER); String passwd=p.getProperty(PASSWORD); ArrayList list=new java.util.ArrayList(); for(int i=0;i<f.length;i++){ list.add(f[i].toURI().toURL()); } URL[] driverURLs=(URL[])list.toArray(new URL[0]); URLClassLoader l = new URLClassLoader(driverURLs); Class c = Class.forName(driver_name, true, l); Driver driver=(Driver)c.newInstance(); Connection con=driver.connect(url,p); return con; }
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()); 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; }
/** * 加载对应路径jar包里的对应驱动 * * @param fname 对应路径 如: lib4/ojdbc14.jar * @param dname 驱动名 如: oracle.jdbc.driver.OracleDriver * @return 加载到的驱动 java.sql.Driver * @throws Exception * @author tangxr */ public static Driver getDriverLoaderByName(String fname, String dname) throws Exception { if (null == fname || "".equals(fname)) { LOG.error("对应的驱动路径不存在,请确认."); return null; } if (null == dname || "".equals(dname)) { LOG.error("对应的驱动类的名字不存在."); return null; } File file = new File(fname); if (!file.exists()) { LOG.error("对应的驱动jar不存在."); return null; } URLClassLoader loader = new URLClassLoader(new URL[]{file.toURI().toURL()}); loader.clearAssertionStatus(); return (Driver) loader.loadClass(dname).newInstance(); }
private void deregisterJdbcDrivers() { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); Enumeration<Driver> drivers = DriverManager.getDrivers(); while (drivers.hasMoreElements()) { LOGGER.debug("Deregistering JDBC Drivers:"); Driver driver = drivers.nextElement(); if (driver.getClass().getClassLoader() == classLoader) { try { LOGGER.debug(" {} v{}.{}", driver.getClass().getName(), driver.getMajorVersion(), driver.getMinorVersion() ); DriverManager.deregisterDriver(driver); } catch (SQLException e) { LOGGER.error("Failed to deregister JDBC driver: ", e); } } } }
@Override public Connection getConnection() throws SQLException { Driver driver = getDriver(); Properties props = new Properties(); if (stringHasValue(userId)) { props.setProperty("user", userId); //$NON-NLS-1$ } if (stringHasValue(password)) { props.setProperty("password", password); //$NON-NLS-1$ } props.putAll(otherProperties); Connection conn = driver.connect(connectionURL, props); if (conn == null) { throw new SQLException(getString("RuntimeError.7")); //$NON-NLS-1$ } return conn; }
/** * Set JDBC Driver class name to use * @param driverClassName JDBC Driver class name */ @SuppressWarnings("unchecked") public void setDriverClassName(String driverClassName) { ObjectUtils.argumentNotNull(driverClassName, "Driver class must be not null"); try { Class<?> driverClass = Class.forName(driverClassName.trim(), true, getClass().getClassLoader()); if (!Driver.class.isAssignableFrom(driverClass)) { throw new IllegalStateException("Class: " + driverClassName + " is not a valid JDBC Driver class"); } setDriverClass((Class<? extends Driver>) driverClass); } catch (ClassNotFoundException e) { throw new IllegalStateException("Failed to load JDBC driver class: " + driverClassName, e); } }
public Connection getConnection(JDBCConnectionConfiguration config) throws SQLException { Driver driver = getDriver(config); Properties props = new Properties(); if (StringUtility.stringHasValue(config.getUserId())) { props.setProperty("user", config.getUserId()); //$NON-NLS-1$ } if (StringUtility.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(Messages.getString("RuntimeError.7")); //$NON-NLS-1$ } return conn; }
/** * 关闭所有连接,撤销驱动程序的注册 */ public synchronized void release() { // 等待直到最后一个客户程序调用 if (--clients != 0) { return; } Enumeration allPools = pools.elements(); while (allPools.hasMoreElements()) { DBConnectionPool pool = (DBConnectionPool) allPools.nextElement(); pool.release(); } Enumeration allDrivers = drivers.elements(); while (allDrivers.hasMoreElements()) { Driver driver = (Driver) allDrivers.nextElement(); try { DriverManager.deregisterDriver(driver); } catch (SQLException e) { } } }
public static Connection getConnection() { try { DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver()); String url = "jdbc:mysql://" + //db type "localhost:" + //host name "3306/" + //port "db_example?" + //db name "useSSL=false&" + //do not use ssl "user=tully&" + //login "password=tully"; //password return DriverManager.getConnection(url); } catch (SQLException e) { throw new RuntimeException(e); } }
public Connection get() { try { DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver()); String url = "jdbc:mysql://" + //db type "localhost:" + //host name "3306/" + //port "db_example?" + //db name "useSSL=false&" + //do not use ssl "user=tully&" + //login "password=tully"; //password return DriverManager.getConnection(url); } catch (SQLException e) { throw new RuntimeException(e); } }
private static Connection makeJDBCConnection() { try { final String catalinaBase = System.getProperty("catalina.base"); final String databaseHome = (new File(catalinaBase, "data/parabuild")).getAbsolutePath(); final Properties props = new Properties(); props.setProperty("user", PersistanceUtils.DATABASE_USER_NAME); props.setProperty("password", PersistanceUtils.DATABASE_PASSWORD); final Driver driver = (Driver) Class.forName("org.hsqldb.jdbcDriver").newInstance(); final Connection connection = driver.connect("jdbc:hsqldb:" + databaseHome, props); connection.setAutoCommit(false); return connection; } catch (Exception e) { final IllegalStateException ise = new IllegalStateException(StringUtils.toString(e)); ise.initCause(e); throw ise; } }
public void init() { if (this.ds == null) { try { Class<? extends Driver> driverClass = (Class<? extends Driver>) Class.forName(this.driverClassName); this.ds = JdbcDataSourceFactory.createFromJdbcUrl(driverClass, this.url, new Credential(this.username, this.password)); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } }
@Test public void acceptsCloudSpannerURL() throws SQLException { Driver driver = getDriver(); assertTrue(driver.acceptsURL( "jdbc:cloudspanner://localhost;Project=adroit-hall-xxx;Instance=test-instance;Database=testdb;PvtKeyPath=C:\\Users\\MyUserName\\Documents\\CloudSpannerKeys\\cloudspanner3.json")); }
/** * Utility method to see if a driver is registered */ private boolean isDriverRegistered(Driver d) { boolean foundDriver = false; java.util.Enumeration e = DriverManager.getDrivers(); while (e.hasMoreElements()) { if (d == (Driver) e.nextElement()) { foundDriver = true; break; } } return foundDriver; }
/** * Deregister a previously registered driver. */ public synchronized void deregisterDriver(Driver driver) { if (registeredDrivers == null) { return; } registeredDrivers.remove(driver); }
private static DataSource getJdbcDs(final Config config, final int numConnections) { String jdbcUrl = config.getString("jdbcUrl"); final String username = config.getString("username"); final String password = config.getString("password"); final String driver = config.getString("driver"); try { return JdbcDataSourceFactory.createFromJdbcUrl( (Class<? extends Driver>) Class.forName(driver), jdbcUrl, new Credential(username, password), numConnections); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } }
/** * Tests that the fallback JDBCDriver instance is used. */ public void testLoadJDBCDriver() throws Exception { JDBCDriver drv = createJDBCDriver(); Connection conn = DbDriverManager.getDefault().getConnection(DriverImpl.DEFAULT_URL, new Properties(), drv); Driver d = ((ConnectionEx)conn).getDriver(); assertSame(DriverImpl.class, d.getClass()); assertTrue(d.acceptsURL(DriverImpl.DEFAULT_URL)); }
public void testNoJDBCDriverLeaks() throws Exception { JDBCDriver drv = createJDBCDriver(); Driver driver = DbDriverManager.getDefault().getDriver(DriverImpl.DEFAULT_URL, drv); Reference drvRef = new WeakReference(drv); drv = null; assertGC("Should be possible to GC the driver", drvRef); }
private DriverPropertyInfo[] getPropertyInfos() { try { String e = this.hostTextField.getText(); if(e == null || "".equals(e)) { e = "192.168.0.0"; } String port = this.portTextField.getText(); if(port == null || "".equals(port)) { port = "1234"; } String db = this.databaseTextField.getText(); if(db == null || "".equals(db)) { db = "test"; } String prop = this.propertyTextField.getText(); if (prop == null || "".equals(prop)) { prop = ""; } String driverURL = FieldConnectionEntry.createURL(this.getJDBCProperties(), e, port, db, prop); Driver driver = DriverManager.getDriver(driverURL); Properties givenProperties = this.currentlyEditedEntry.getConnectionProperties(); DriverPropertyInfo[] propertyInfo = driver.getPropertyInfo(driverURL, givenProperties); if(propertyInfo == null) { propertyInfo = new DriverPropertyInfo[0]; } return propertyInfo; } catch (SQLException var8) { LogService.getRoot().log(Level.SEVERE, "com.rapidminer.gui.tools.dialogs.DatabaseConnectionDialog.loading_jdbc_driver_properties_error", var8); return null; } }
private List<String> findDrivers(final File file) { final LinkedList driverNames = new LinkedList(); (new ProgressThread("manage_database_drivers.scan_jar", true) { public void run() { try { ClassLoader e = (ClassLoader)AccessController.doPrivileged(new PrivilegedExceptionAction() { public ClassLoader run() throws Exception { try { return new URLClassLoader(new URL[]{file.toURI().toURL()}); } catch (MalformedURLException var2) { throw new RuntimeException("Cannot create class loader for file \'" + file + "\': " + var2.getMessage(), var2); } } }); try { JarFile e1 = new JarFile(file); Tools.findImplementationsInJar(e, e1, Driver.class, driverNames); } catch (Exception var3) { LogService.getRoot().log(Level.WARNING, I18N.getMessage(LogService.getRoot().getResourceBundle(), "com.rapidminer.gui.tools.dialogs.ManageDatabaseDriversDialog.scanning_jar_file_error", new Object[]{file, var3.getMessage()}), var3); } } catch (PrivilegedActionException var4) { throw new RuntimeException("Cannot create class loader for file \'" + file + "\': " + var4.getMessage(), var4); } } }).startAndWait(); return driverNames; }
public List<String> clearJdbcDriverRegistrations() throws SQLException { List<String> driverNames = new ArrayList<String>(); /* * DriverManager.getDrivers() has a nasty side-effect of registering * drivers that are visible to this class loader but haven't yet been * loaded. Therefore, the first call to this method a) gets the list of * originally loaded drivers and b) triggers the unwanted side-effect. * The second call gets the complete list of drivers ensuring that both * original drivers and any loaded as a result of the side-effects are * all de-registered. */ HashSet<Driver> originalDrivers = new HashSet<Driver>(); Enumeration<Driver> drivers = DriverManager.getDrivers(); while (drivers.hasMoreElements()) { originalDrivers.add(drivers.nextElement()); } drivers = DriverManager.getDrivers(); while (drivers.hasMoreElements()) { Driver driver = drivers.nextElement(); // Only unload the drivers this web app loaded if (driver.getClass().getClassLoader() != this.getClass().getClassLoader()) { continue; } // Only report drivers that were originally registered. Skip any // that were registered as a side-effect of this code. if (originalDrivers.contains(driver)) { driverNames.add(driver.getClass().getCanonicalName()); } DriverManager.deregisterDriver(driver); } return driverNames; }
/** * Load the driver using ServiceLoader */ @Test public void testLoadDriverServiceLoader() { ServiceLoader<Driver> sl = ServiceLoader.load(Driver.class); for(Iterator<Driver> it = sl.iterator(); it.hasNext(); ) { Driver driver = it.next(); if (driver instanceof com.dremio.jdbc.Driver) { return; } } Assert.fail("com.dremio.jdbc.Driver not found using ServiceLoader"); }
public List<String> clearJdbcDriverRegistrations() throws SQLException { List<String> driverNames = new ArrayList<String>(); /* * DriverManager.getDrivers() has a nasty side-effect of registering * drivers that are visible to this class loader but haven't yet been * loaded. Therefore, the first call to this method a) gets the list * of originally loaded drivers and b) triggers the unwanted * side-effect. The second call gets the complete list of drivers * ensuring that both original drivers and any loaded as a result of the * side-effects are all de-registered. */ HashSet<Driver> originalDrivers = new HashSet<Driver>(); Enumeration<Driver> drivers = DriverManager.getDrivers(); while (drivers.hasMoreElements()) { originalDrivers.add(drivers.nextElement()); } drivers = DriverManager.getDrivers(); while (drivers.hasMoreElements()) { Driver driver = drivers.nextElement(); // Only unload the drivers this web app loaded if (driver.getClass().getClassLoader() != this.getClass().getClassLoader()) { continue; } // Only report drivers that were originally registered. Skip any // that were registered as a side-effect of this code. if (originalDrivers.contains(driver)) { driverNames.add(driver.getClass().getCanonicalName()); } DriverManager.deregisterDriver(driver); } return driverNames; }
/** * 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)); }
private void initSql() { String path = "db.sql"; try(InputStream script = new FileInputStream(path)){ String sql = IOUtils.toString(script, StandardCharsets.UTF_8); Properties info = new Properties(); info.put("user", postgres.getUsername()); info.put("password", postgres.getPassword()); Driver driver = new org.postgresql.Driver(); try(Connection connection = driver.connect(postgres.getJdbcUrl(), info)){ ScriptUtils.executeSqlScript(connection, path, sql); } } catch (IOException | SQLException | ScriptException e) { throw new RuntimeException(e); } }
public void connect(){ if(this.host != null || this.port != null || this.user != null || this.password != null) { try{ Class.forName("oracle.jdbc.OraclePreparedStatement", true, ResourceMaping.getInstance().getJARClassLoader()); Driver driver = (Driver) Class.forName("oracle.jdbc.driver.OracleDriver", true, ResourceMaping.getInstance().getJARClassLoader()).newInstance(); DriverManager.registerDriver(new DelegatingDriver(driver)); this.con = DriverManager.getConnection( "jdbc:oracle:thin:@"+this.host+":"+this.port+":"+this.db, this.user, this.password); this.stmt = this.con.createStatement(); } catch(Exception e){ this.Pool.closeConnection(this); System.out.println("Existe un error al conectar con la base de datos - ERROR: 01"); System.out.println("------------------------------------------------------------------------------------------------------------------------------------------------------------"); System.out.println("Host --> " + this.host); System.out.println("Port --> " + this.port); System.out.println("Db --> " + this.db); System.out.println("User --> " + this.user); System.out.println("Pass --> " + this.password); System.out.println("============================================================================================================================================================"); e.printStackTrace(); System.out.println("------------------------------------------------------------------------------------------------------------------------------------------------------------"); } } else { System.out.println("Faltan datos para iniciar una conección con la DB Oracle. ERROR 02"); } }
public DelegatingDriver(Driver driver) { if (driver == null) { throw new IllegalArgumentException("Driver must not be null."); } this.driver = driver; }
protected static String getProperty(String property, String connectionString, Driver dbDriver){ String ret = null; if(property != null && !property.isEmpty() && dbDriver != null && connectionString != null && !connectionString.isEmpty()){ try { for (DriverPropertyInfo dpi : dbDriver.getPropertyInfo(connectionString, null)) { if(property.equalsIgnoreCase(dpi.name.trim())){ ret = dpi.value; break; } } } catch (SQLException e) {} } return ret; }
public Connection connect(String url, Properties info) throws SQLException { Driver d = getDriverLoading(url); if(d == null) { return null; } lastUnderlyingDriverRequested = d; Connection c = d.connect(url, info); if(c == null) { throw new SQLException("invalid or unknown driver url: " + url); } if(log.isJdbcLoggingEnabled()) { ConnectionSpy cspy = new ConnectionSpy(c); RdbmsSpecifics r = null; String dclass = d.getClass().getName(); if(dclass != null && dclass.length() > 0) { r = (RdbmsSpecifics) rdbmsSpecifics.get(dclass); } if(r == null) { r = defaultRdbmsSpecifics; } cspy.setRdbmsSpecifics(r); return cspy; } else { return c; } }
public String[] getDriverNames() { int i=0; List<Driver> drivers = getDrivers(); String[] driverNames = new String[drivers.size()]; for (Driver driver : drivers) driverNames[i++] = driver.getClass().getName(); return driverNames; }
private boolean loadDriver() { try { DriverManager.registerDriver((Driver) Class.forName(driver).newInstance()); return true; } catch (Exception e) { PrintHelper.printError(" Load Database driver fail : " + e); } return false; }