List of usage examples for java.sql DriverManager registerDriver
public static void registerDriver(java.sql.Driver driver) throws SQLException
From source file:org.miloss.fgsms.common.Utility.java
@Deprecated private static Connection getConfigurationDB_NONPOOLED_Connection_FAILOVER() { try {// w w w .j a v a2 s .c o m Properties prop = PropertyLoader.loadProperties(PropertyFilePath); Driver d = (Driver) Class.forName(prop.getProperty(DBdriver)).newInstance(); DriverManager.registerDriver(d); Connection con = DriverManager.getConnection(prop.getProperty(ConfigDBURL_FAILOVER), prop.getProperty(ConfigUsername_FAILOVER), DE(prop.getProperty(ConfigPassword_FAILOVER))); PreparedStatement com = con.prepareStatement("select 1;"); try { com.execute(); DBUtils.safeClose(com); return con; } catch (Exception e) { log.log(Level.FATAL, "Error obtaining failover config database connection, attempting alternate. msg:" + e.getLocalizedMessage(), e); return null; } finally { DBUtils.safeClose(com); } } catch (Exception ex) { log.log(Level.FATAL, "Error obtaining primary conf database connection:" + ex.getLocalizedMessage(), ex); return null; } }
From source file:org.apache.phoenix.query.BaseTest.java
/** * Create a {@link PhoenixTestDriver} and register it. * @return an initialized and registered {@link PhoenixTestDriver} *//*from ww w . j a va 2s. co m*/ public static PhoenixTestDriver initAndRegisterTestDriver(String url, ReadOnlyProps props) throws Exception { PhoenixTestDriver newDriver = new PhoenixTestDriver(props); DriverManager.registerDriver(newDriver); Driver oldDriver = DriverManager.getDriver(url); if (oldDriver != newDriver) { destroyDriver(oldDriver); } Properties driverProps = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = newDriver.connect(url, driverProps); conn.close(); return newDriver; }
From source file:uk.chromis.pos.forms.JRootApp.java
private void superUserLogin() { //lets check if the super user exists AppUser user = null;//from w w w .java2 s. co m try { user = m_dlSystem.getsuperuser(); if (user == null) { ClassLoader cloader = new URLClassLoader(new URL[] { new File(AppConfig.getInstance().getProperty("db.driverlib")).toURI().toURL() }); DriverManager.registerDriver(new DriverWrapper((Driver) Class .forName(AppConfig.getInstance().getProperty("db.driver"), true, cloader).newInstance())); Class.forName(AppConfig.getInstance().getProperty("db.driver")); con = DriverManager.getConnection(db_url, db_user, db_password); PreparedStatement stmt = con.prepareStatement( "INSERT INTO PEOPLE (ID, NAME, ROLE, VISIBLE) VALUES ('99', 'SuperAdminUser', '0', true)"); stmt.executeUpdate(); user = m_dlSystem.getsuperuser(); } } catch (BasicException e) { } catch (SQLException | MalformedURLException | ClassNotFoundException | InstantiationException | IllegalAccessException ex) { Logger.getLogger(JRootApp.class.getName()).log(Level.SEVERE, null, ex); } openAppView(user); }
From source file:org.apache.phoenix.monitoring.PhoenixMetricsIT.java
@Test public void testGetConnectionsWithDifferentJDBCParamsConcurrently() throws Exception { DriverManager.registerDriver(PhoenixDriver.INSTANCE); ExecutorService exec = Executors.newFixedThreadPool(4); // establish url and quorum. Need to use PhoenixDriver and not PhoenixTestDriver String zkQuorum = "localhost:" + getUtility().getZkCluster().getClientPort(); String baseUrl = PhoenixRuntime.JDBC_PROTOCOL + PhoenixRuntime.JDBC_PROTOCOL_SEPARATOR + zkQuorum; int numConnections = 20; List<Callable<Connection>> callables = new ArrayList<>(numConnections); List<Future<Connection>> futures = new ArrayList<>(numConnections); try {/*from w w w . j av a 2 s . com*/ GLOBAL_HCONNECTIONS_COUNTER.getMetric().reset(); GLOBAL_QUERY_SERVICES_COUNTER.getMetric().reset(); assertEquals(0, GLOBAL_HCONNECTIONS_COUNTER.getMetric().getValue()); assertEquals(0, GLOBAL_QUERY_SERVICES_COUNTER.getMetric().getValue()); for (int i = 1; i <= numConnections; i++) { String customUrl = baseUrl + ':' + CUSTOM_URL_STRING + '=' + i; Callable<Connection> c = new GetConnectionCallable(customUrl + ";"); callables.add(c); futures.add(exec.submit(c)); } for (int i = 0; i < futures.size(); i++) { futures.get(i).get(); } assertEquals(numConnections, GLOBAL_HCONNECTIONS_COUNTER.getMetric().getValue()); assertEquals(numConnections, GLOBAL_QUERY_SERVICES_COUNTER.getMetric().getValue()); } finally { exec.shutdownNow(); for (int i = 0; i < futures.size(); i++) { try { Connection c = futures.get(i).get(); // close the query services instance because we created a lot of HConnections. c.unwrap(PhoenixConnection.class).getQueryServices().close(); c.close(); } catch (Exception ignore) { } } } }
From source file:org.apache.nifi.cdc.mysql.processors.CaptureChangeMySQL.java
protected void registerDriver(String locationString, String drvName) throws InitializationException { if (locationString != null && locationString.length() > 0) { try {/*from ww w . j a v a 2s.com*/ // Split and trim the entries final ClassLoader classLoader = ClassLoaderUtils.getCustomClassLoader(locationString, this.getClass().getClassLoader(), (dir, name) -> name != null && name.endsWith(".jar")); // Workaround which allows to use URLClassLoader for JDBC driver loading. // (Because the DriverManager will refuse to use a driver not loaded by the system ClassLoader.) final Class<?> clazz = Class.forName(drvName, true, classLoader); if (clazz == null) { throw new InitializationException("Can't load Database Driver " + drvName); } final Driver driver = (Driver) clazz.newInstance(); DriverManager.registerDriver(new DriverShim(driver)); } catch (final InitializationException e) { throw e; } catch (final MalformedURLException e) { throw new InitializationException("Invalid Database Driver Jar Url", e); } catch (final Exception e) { throw new InitializationException("Can't load Database Driver", e); } } }
From source file:org.nuxeo.launcher.config.ConfigurationGenerator.java
/** * Check driver availability and database connection * * @param databaseTemplate Nuxeo database template * @param dbName nuxeo.db.name parameter in nuxeo.conf * @param dbUser nuxeo.db.user parameter in nuxeo.conf * @param dbPassword nuxeo.db.password parameter in nuxeo.conf * @param dbHost nuxeo.db.host parameter in nuxeo.conf * @param dbPort nuxeo.db.port parameter in nuxeo.conf * @throws DatabaseDriverException/*from w w w . j av a 2s . c o m*/ * @throws IOException * @throws FileNotFoundException * @throws SQLException * @since 5.6 */ public void checkDatabaseConnection(String databaseTemplate, String dbName, String dbUser, String dbPassword, String dbHost, String dbPort) throws FileNotFoundException, IOException, DatabaseDriverException, SQLException { File databaseTemplateDir = new File(nuxeoHome, TEMPLATES + File.separator + databaseTemplate); Properties templateProperties = loadTrimmedProperties(new File(databaseTemplateDir, NUXEO_DEFAULT_CONF)); String classname, connectionUrl; if (userConfig.getProperty(PARAM_TEMPLATE_DBNAME).equals(databaseTemplateDir)) { // userConfig already includes databaseTemplate classname = userConfig.getProperty(PARAM_DB_DRIVER); connectionUrl = userConfig.getProperty(PARAM_DB_JDBC_URL); } else { // testing a databaseTemplate not included in userConfig // check if value is set in nuxeo.conf if (userConfig.containsKey(PARAM_DB_DRIVER)) { classname = (String) userConfig.get(PARAM_DB_DRIVER); } else { classname = templateProperties.getProperty(PARAM_DB_DRIVER); } if (userConfig.containsKey(PARAM_DB_JDBC_URL)) { connectionUrl = (String) userConfig.get(PARAM_DB_JDBC_URL); } else { connectionUrl = templateProperties.getProperty(PARAM_DB_JDBC_URL); } } // Load driver class from template or default lib directory Driver driver = lookupDriver(databaseTemplate, databaseTemplateDir, classname); // Test db connection DriverManager.registerDriver(driver); Properties ttProps = new Properties(userConfig); ttProps.put(PARAM_DB_HOST, dbHost); ttProps.put(PARAM_DB_PORT, dbPort); ttProps.put(PARAM_DB_NAME, dbName); ttProps.put(PARAM_DB_USER, dbUser); ttProps.put(PARAM_DB_PWD, dbPassword); TextTemplate tt = new TextTemplate(ttProps); String url = tt.processText(connectionUrl); Properties conProps = new Properties(); conProps.put("user", dbUser); conProps.put("password", dbPassword); log.debug("Testing URL " + url + " with " + conProps); Connection con = driver.connect(url, conProps); con.close(); }
From source file:HW3.java
private Connection openConnection() throws SQLException, ClassNotFoundException { DriverManager.registerDriver(new oracle.jdbc.OracleDriver()); String userName = "Scott"; String dbURL = "jdbc:oracle:thin:@localhost:1521:orcl"; String pass = "Najuka123"; return DriverManager.getConnection(dbURL, userName, pass); }
From source file:us.daveread.basicquery.BasicQuery.java
/** * Loads the driver into the JVM making it available for usage by the * driver class/*from www. jav a 2s . c o m*/ * * @param driverClass * String specifying the class name for the driver * @param productName * String specifying the product name - oracle,sybase or * mySql * @param dbClassLoader * The classloader for accessing DB drivers */ private void loadDriver(String driverClass, String productName, DynamicClassLoader dbClassLoader) { Constructor<?> constructDriver; try { constructDriver = Class.forName(driverClass, true, dbClassLoader).getConstructor(); DriverManager.registerDriver(new DynamicDriver((Driver) constructDriver.newInstance())); messageOut(Resources.getString("msgDriverLoaded", productName), STYLE_GREEN); } catch (Exception any) { LOGGER.error("Unable to load DB driver [" + driverClass + "]", any); messageOut(Resources.getString("errDriverNotFound", productName), STYLE_RED); } }
From source file:com.virtusa.isq.vtaf.runtime.SeleniumTestBase.java
/** * Creates the db connection.//from www .jav a2 s . co m * * @param databaseType * the database type * @param instanceName * the instance name * @param url * the url * @param username * the username * @param password * the password */ public final void createDBConnection(final String databaseType, final String instanceName, final String url, final String username, final String password) { Connection con = null; boolean isNewInstance; if (getDatabaseInstances().containsKey(instanceName)) { isNewInstance = false; } else { isNewInstance = true; } if (isNewInstance) { try { if ("mysql".equalsIgnoreCase(databaseType)) { String dbClass = "com.mysql.jdbc.Driver"; Class.forName(dbClass).newInstance(); con = DriverManager.getConnection(url, username, password); } else if ("oracle".equalsIgnoreCase(databaseType)) { DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()); con = DriverManager.getConnection(url, username, password); } else if ("mssql".equalsIgnoreCase(databaseType)) { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); con = DriverManager.getConnection(url, username, password); } else if (databaseType.isEmpty()) { reportresult(true, "CREATE DB CONNECTION :", "FAILED", "Database type not selected"); checkTrue(false, true, "CREATE DB CONNECTION command: Error :- No database type selected."); } putDatabaseInstances(instanceName, con); reportresult(true, "CREATE DB CONNECTION :", "PASSED", "Instance name : " + instanceName + " DB URL : " + url + ""); } catch (SQLException e) { e.printStackTrace(); reportresult(true, "CREATE DB CONNECTION :", "FAILED", e.getMessage()); checkTrue(false, true, "CREATE DB CONNECTION command: Error :- " + e.getMessage()); } catch (Exception e) { e.printStackTrace(); reportresult(true, "CREATE DB CONNECTION :", "FAILED", e.getMessage()); checkTrue(false, true, "CREATE DB CONNECTION command: Error :- " + e.getMessage()); } } }