private Connection openConnection(Class<? extends Driver> driverClass, Properties properties) throws Exception { assert properties != null; try { return DriverManager.getConnection(url, properties); } catch (Exception e) { // if the current class loader can not access the driver class, create driver class directly try { Driver driverObject = driverClass.getConstructor().newInstance(); Connection connection = driverObject.connect(url, properties); if (connection == null) { throw new IllegalStateException( MessageFormat.format( "Driver class {0} may not support {1}", driverClass.getName(), url)); } return connection; } catch (RuntimeException inner) { LOG.debug( MessageFormat.format( "Failed to resolve driver class (internal error): {0} (on {1})", driverClass.getName(), driverClass.getClassLoader()), e); } catch (Exception inner) { LOG.debug( MessageFormat.format( "Failed to resolve driver class: {0} (on {1})", driverClass.getName(), driverClass.getClassLoader()), e); } throw e; } }
public static void connectToDB() throws Exception { if (connection == null) { info = new Properties(); info.load(new FileInputStream("src/java-test/tests.properties")); url = info.getProperty("url"); driver = (Driver) Class.forName( DatabaseFactory.getInstance().findDefaultDriver(url), true, Thread.currentThread().getContextClassLoader()) .newInstance(); connection = driver.connect(url, info); if (connection == null) { throw new DatabaseException( "Connection could not be created to " + url + " with driver " + driver.getClass().getName() + ". Possibly the wrong driver for the given database URL"); } jdbcConnection = new JdbcConnection(connection); } }
public static void main(String[] args) { Connection conn = null; try { // Step 1: connect to database server Driver d = new SimpleDriver(); conn = d.connect("jdbc:simpledb://localhost", null); // Step 2: execute the query Statement stmt = conn.createStatement(); String qry = "select SName, DName " + "from DEPT, STUDENT " + "where MajorId = DId"; ResultSet rs = stmt.executeQuery(qry); // Step 3: loop through the result set System.out.println("Name\tMajor"); while (rs.next()) { String sname = rs.getString("SName"); String dname = rs.getString("DName"); System.out.println(sname + "\t" + dname); } rs.close(); } catch (SQLException e) { e.printStackTrace(); } finally { // Step 4: close the connection try { if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }
public void executeQuery() throws SQLException { log( "select account, branch, balance, filler from " + m_Driver.getAccountName() + " where account < 101\n", 2); Statement stmt = null; try { stmt = m_conn.createStatement(); ResultSet set = stmt.executeQuery( "select account, branch, balance, filler from " + m_Driver.getAccountName() + " where account < 101"); while (set.next()) { set.getInt(1); set.getInt(2); set.getDouble(3); set.getString(4); } set.close(); } finally { if (stmt != null) stmt.close(); stmt = null; } }
/** * Must be executed as part of a test suite that opens the database connection. * * @throws Exception Flow network error. */ @Override protected void define() throws Exception { /** * String userHome = System.getProperty("user.home"); StringBuilder sb = new StringBuilder(); * String[] subStr = userHome.split("\\Q\\\\E"); for (String subStr1 : subStr) { * sb.append(subStr1); sb.append("/"); } sb.append(".fbpTest/db"); String dbName = * sb.toString(); String connectionURL = "jdbc:derby:" + dbName + ";create=true"; * System.out.println("Insert Test '" + connectionURL + "'"); * SingletonDbWrapper.instance().setConnectionUrl(connectionURL); * * <p>conn = SingletonDbWrapper.instance().getConnection(); */ Enumeration<Driver> dList = DriverManager.getDrivers(); while (dList.hasMoreElements()) { Driver aDriver = dList.nextElement(); System.out.println(aDriver.toString()); } tableStruct(); component("DbInsert", Insert.class); component("Output", Output.class); connect( component("DbInsert"), port(Insert.OP), component("Output"), port("IN")); // connect("DbInsert.COMPLETION_STATUS", "Output.IN"); String insertStmt = "INSERT INTO TEST_ONE (TEXT_STRING, INT_VALUE)" + " VALUES (?, ?)"; Map<String, Object> params = new HashMap(); params.put(RDB_CONNECTION, conn); params.put(SQL_INSERT_STATEMENT_KEY, insertStmt); params.put(Integer.toString(0), "String"); params.put(Integer.toString(1), "Integer"); initialize(params, component("DbInsert"), port(Insert.IIP)); String[] recd01 = {"First Value", "12"}; initialize(recd01, component("DbInsert"), port(Insert.IP)); }
@Override public void destroy() { super.destroy(); Enumeration<Driver> e = DriverManager.getDrivers(); while (e.hasMoreElements()) { Driver driver = e.nextElement(); try { if (driver.getClass().getClassLoader() == getClass().getClassLoader()) DriverManager.deregisterDriver(driver); } catch (SQLException e1) { LOG.logError("Cannot unload driver: " + driver); } } LogFactory.releaseAll(); LogManager.shutdown(); // SLF4JLogFactory.releaseAll(); // should be the same as the LogFactory.releaseAll call Iterator<Class<?>> i = IIORegistry.getDefaultInstance().getCategories(); while (i.hasNext()) { Class<?> c = i.next(); Iterator<?> k = IIORegistry.getDefaultInstance().getServiceProviders(c, false); while (k.hasNext()) { Object o = k.next(); if (o.getClass().getClassLoader() == getClass().getClassLoader()) { IIORegistry.getDefaultInstance().deregisterServiceProvider(o); LOG.logDebug("Deregistering JAI driver ", o.getClass()); } } } Introspector.flushCaches(); // just clear the configurations for now, it does not hurt CRSConfiguration.DEFINED_CONFIGURATIONS.clear(); }
private void initializeDriver() { if (_jdbcUrl == null) { throw new IllegalStateException("JDBC URL is null, cannot create connection!"); } logger.debug("Determining if driver initialization is nescesary"); // it's best to avoid initializing the driver, so we do this check. // It may already have been initialized and Class.forName(...) does // not always work if the driver is in a different classloader boolean installDriver = true; Enumeration<Driver> drivers = DriverManager.getDrivers(); while (drivers.hasMoreElements()) { Driver driver = drivers.nextElement(); try { if (driver.acceptsURL(_jdbcUrl)) { installDriver = false; break; } } catch (Exception e) { logger.warn("Driver threw exception when acceptURL(...) was invoked", e); } } if (installDriver) { try { Class.forName(_driverClass); } catch (ClassNotFoundException e) { throw new IllegalStateException("Could not initialize JDBC driver", e); } } }
/** {@inheritDoc} */ public void connect(InetAddress address, int port, int timeout) throws IOException, Exception { log().info("connecting to JDBC on " + address); if (log().isDebugEnabled()) { log().debug("Loading JDBC driver: '" + getDbDriver() + "'"); } Driver driver = (Driver) Class.forName(getDbDriver()).newInstance(); if (log().isDebugEnabled()) { log().debug("JDBC driver loaded: '" + getDbDriver() + "'"); } String url = DBTools.constructUrl(getUrl(), address.getCanonicalHostName()); if (log().isDebugEnabled()) { log().debug("Constructed JDBC url: '" + url + "'"); } Properties props = new Properties(); props.setProperty("user", getUser()); props.setProperty("password", getPassword()); props.setProperty("timeout", String.valueOf(timeout / 1000)); m_connection = driver.connect(url, props); if (log().isDebugEnabled()) { log() .debug( "Got database connection: '" + m_connection + "' (" + url + ", " + getUser() + ", " + getPassword() + ")"); } }
@Override public void run() { Connection conn = null; try { Driver d = new SimpleDriver(); conn = d.connect("jdbc:simpledb://localhost", null); // conn.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); Statement stmt = conn.createStatement(); // try { // Thread.sleep(5000); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } for (int i = 0; i < 3; i++) { String cmd; if (i % 2 == 0) cmd = "update STUDENT set MajorId=30 " + "where SName = 'amy'"; else cmd = "update STUDENT set MajorId=20 " + "where SName = 'amy'"; stmt.executeUpdate(cmd); System.out.println("Amy's major changed."); } } catch (SQLException e) { e.printStackTrace(); } finally { try { System.out.println(conn.getTransactionIsolation()); if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }
/** * Get a Connection to the database from the underlying driver that this DriverSpy is spying on. * If logging is not enabled, an actual Connection to the database returned. If logging is * enabled, a ConnectionSpy object which wraps the real Connection is returned. * * @param url JDBC connection URL . * @param info a list of arbitrary string tag/value pairs as connection arguments. Normally at * least a "user" and "password" property should be included. * @return a <code>Connection</code> object that represents a connection to the URL. * @throws SQLException if a database access error occurs */ public Connection connect(String url, Properties info) throws SQLException { Driver d = getUnderlyingDriver(url); if (d == null) { return null; } // get actual URL that the real driver expects // (strip off "jdbc:log4" from url) url = url.substring(9); 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 static void main(String[] args) { try { Driver d = new SimpleDriver(); conn = d.connect("jdbc:simpledb://localhost", null); Reader rdr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(rdr); while (true) { // process one line of input System.out.print("\nSQL> "); String cmd = br.readLine().trim(); System.out.println(); if (cmd.startsWith("exit")) break; else if (cmd.startsWith("select")) doQuery(cmd); else doUpdate(cmd); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (conn != null) conn.close(); } catch (Exception e) { e.printStackTrace(); } } }
/** * Clearing the in-memory configuration parameters, we will receive notification that the servlet * context is about to be shut down */ @Override public void contextDestroyed(ServletContextEvent sce) { synchronized (servletContext) { logger.info("Webapp shutdown"); // XXX Paul: grabbed this from // http://opensource.atlassian.com/confluence/spring/display/DISC/Memory+leak+-+classloader+won%27t+let+go // in hopes that we can clear all the issues with J2EE containers // during shutdown try { ServletContext ctx = sce.getServletContext(); // prepare spring for shutdown Introspector.flushCaches(); // dereg any drivers for (Enumeration e = DriverManager.getDrivers(); e.hasMoreElements(); ) { Driver driver = (Driver) e.nextElement(); if (driver.getClass().getClassLoader() == getClass().getClassLoader()) { DriverManager.deregisterDriver(driver); } } // shutdown jmx JMXAgent.shutdown(); // shutdown the persistence thread FilePersistenceThread persistenceThread = FilePersistenceThread.getInstance(); if (persistenceThread != null) { persistenceThread.shutdown(); } // shutdown spring Object attr = ctx.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); if (attr != null) { // get web application context from the servlet context ConfigurableWebApplicationContext applicationContext = (ConfigurableWebApplicationContext) attr; ConfigurableBeanFactory factory = applicationContext.getBeanFactory(); // for (String scope : factory.getRegisteredScopeNames()) { // logger.debug("Registered scope: " + scope); // } try { for (String singleton : factory.getSingletonNames()) { logger.debug("Registered singleton: " + singleton); factory.destroyScopedBean(singleton); } } catch (RuntimeException e) { } factory.destroySingletons(); ctx.removeAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); applicationContext.close(); } getContextLoader().closeWebApplicationContext(ctx); // org.apache.commons.logging.LogFactory.releaseAll(); // org.apache.log4j.LogManager.getLoggerRepository().shutdown(); // org.apache.log4j.LogManager.shutdown(); } catch (Throwable e) { e.printStackTrace(); } } }
/** * Gets information about the possible properties for the underlying driver. * * @param url the URL of the database to which to connect * @param info a proposed list of tag/value pairs that will be sent on connect open * @return an array of <code>DriverPropertyInfo</code> objects describing possible properties. * This array may be an empty array if no properties are required. * @throws SQLException if a database access error occurs */ public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException { Driver d = getUnderlyingDriver(url); if (d == null) { return new DriverPropertyInfo[0]; } lastUnderlyingDriverRequested = d; return d.getPropertyInfo(url, info); }
@Test public void testStateNotSupportedException() throws SQLException { RuntimeException runtimeException = new RuntimeException(new SQLException("test", HiveDriver.SQL_STATE_NOT_SUPPORTED, null)); when(delegate.acceptsURL(testUrl)).thenReturn(true); when(delegate.connect(testUrl, properties)).thenThrow(runtimeException); assertNull(hiveDriver.connect(testUrl, properties)); verify(delegate).connect(testUrl, properties); }
@Override public boolean acceptsURL(final String url) throws SQLException { String translatedUrl = translate(url); for (Driver driver : getAllDrivers()) { if (driver.acceptsURL(translatedUrl)) { return true; } } return false; }
@Test public void testVersionConstructor() throws Throwable { int majorVersion = 22; int minorVersion = 33; when(driver.getMajorVersion()).thenReturn(majorVersion); when(driver.getMinorVersion()).thenReturn(minorVersion); assertTrue(impalaDatabaseMeta.isDriverVersion(majorVersion, minorVersion)); assertFalse(impalaDatabaseMeta.isDriverVersion(majorVersion, minorVersion + 1)); assertFalse(impalaDatabaseMeta.isDriverVersion(majorVersion + 1, minorVersion)); }
public synchronized void serialEvent(SerialPortEvent oEvent) { try { switch (oEvent.getEventType()) { case SerialPortEvent.DATA_AVAILABLE: if (input == null) { System.out.println("here11"); input = new BufferedReader(new InputStreamReader(serialPort.getInputStream())); } String inputLine = input.readLine(); // System.out.println(input.readLine().trim()); if (inputLine.equals("")) { } else { String url = "jdbc:mysql://localhost/secureplanet"; Properties prop = new Properties(); prop.setProperty("user", "root"); prop.setProperty("password", "toor"); Driver d = new com.mysql.jdbc.Driver(); Connection conn = d.connect(url, prop); if (conn == null) { System.out.println("connection failed"); return; } DatabaseMetaData dm = conn.getMetaData(); String dbversion = dm.getDatabaseProductVersion(); String dbname = dm.getDatabaseProductName(); System.out.println("name:" + dbname); System.out.println("version:" + dbversion); String rfidtoken = inputLine.trim(); Statement stmt = conn.createStatement(); Double lat = 17.4416; Double lng = 78.3826; String sql = "INSERT INTO smarttracking " + "VALUES ('" + rfidtoken + "','" + lat + "','" + lng + "')"; stmt.executeUpdate(sql); } break; default: break; } } catch (Exception e) { e.printStackTrace(); } }
public void close() { Connection connection = (Connection) getRawConnection(); if (connection == null) { return; } synchronized (sDerbyConnections) { int count = ((Integer) sConnectionReferenceCount.get(connection)).intValue(); if (count == 1) { /* * If this is the last reference to the connection, close the * connection. */ String baseDBURL = getBaseDBURL(); try { /* The particulars of closing the connection. */ String driverClass = getDriverDefinition() .getProperty(IJDBCDriverDefinitionConstants.DRIVER_CLASS_PROP_ID); Driver driver = (Driver) connection.getClass().getClassLoader().loadClass(driverClass).newInstance(); driver.connect( baseDBURL + ";shutdown=true", // $NON-NLS-1$ new Properties()); } catch (InstantiationException e) { /* * We shouldn't see this, because we needed this to create * the connection */ } catch (IllegalAccessException e) { /* * We shouldn't see this, because we needed this to create * the connection */ } catch (ClassNotFoundException e) { /* * We shouldn't see this, because we needed this to create * the connection */ } catch (SQLException e) { // Successfully closed the connection sConnectionReferenceCount.remove(connection); sDerbyConnections.remove(baseDBURL); } catch (Exception e) { /* * Can't get the driver. This might happen if the user * modified or deleted the driver definition in the time * since this connection was created. */ } } else { /* Otherwise, just decrement the reference count. */ sConnectionReferenceCount.put(connection, new Integer(--count)); } } }
@Override public DriverPropertyInfo[] getPropertyInfo(final String url, final Properties info) throws SQLException { String translatedUrl = translate(url); for (Driver driver : getAllDrivers()) { if (driver.acceptsURL(translatedUrl)) { return driver.getPropertyInfo(translatedUrl, info); } } return null; }
@Test(expected = RuntimeException.class) public void testException() throws SQLException { RuntimeException runtimeException = new RuntimeException(); when(delegate.acceptsURL(testUrl)).thenReturn(true); when(delegate.connect(testUrl, properties)).thenThrow(runtimeException); try { hiveDriver.connect(testUrl, properties); } catch (Exception e) { assertEquals(runtimeException, e); throw e; } }
/** {@inheritDoc} */ @Override public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final Module module = deploymentUnit.getAttachment(Attachments.MODULE); final ServicesAttachment servicesAttachment = deploymentUnit.getAttachment(Attachments.SERVICES); if (module != null && servicesAttachment != null) { final ModuleClassLoader classLoader = module.getClassLoader(); final List<String> driverNames = servicesAttachment.getServiceImplementations(Driver.class.getName()); for (String driverClassName : driverNames) { try { final Class<? extends Driver> driverClass = classLoader.loadClass(driverClassName).asSubclass(Driver.class); final Constructor<? extends Driver> constructor = driverClass.getConstructor(); final Driver driver = constructor.newInstance(); final int majorVersion = driver.getMajorVersion(); final int minorVersion = driver.getMinorVersion(); final boolean compliant = driver.jdbcCompliant(); if (compliant) { log.infof( "Deploying JDBC-compliant driver %s (version %d.%d)", driverClass, Integer.valueOf(majorVersion), Integer.valueOf(minorVersion)); } else { log.infof( "Deploying non-JDBC-compliant driver %s (version %d.%d)", driverClass, Integer.valueOf(majorVersion), Integer.valueOf(minorVersion)); } String driverName = deploymentUnit.getName(); InstalledDriver driverMetadata = new InstalledDriver( driverName, driverClass.getName(), null, majorVersion, minorVersion, compliant); DriverService driverService = new DriverService(driverMetadata, driver); phaseContext .getServiceTarget() .addService( ServiceName.JBOSS.append("jdbc-driver", driverName.replaceAll(".", "_")), driverService) .addDependency( ConnectorServices.JDBC_DRIVER_REGISTRY_SERVICE, DriverRegistry.class, driverService.getDriverRegistryServiceInjector()) .setInitialMode(Mode.ACTIVE) .install(); } catch (Exception e) { log.warnf("Unable to instantiate driver class \"%s\": %s", driverClassName, e); } } } }
@Override public Connection connect(final String url, final Properties info) throws SQLException { String translatedUrl = translate(url); for (Driver driver : getAllDrivers()) { if (driver.acceptsURL(translatedUrl)) { Connection conn = driver.connect(translatedUrl, info); if (conn != null) { return conn; } } } return null; }
private String findDriverByUrlImpl(String url) { for (int i = 0; i < _driverList.size(); i++) { try { Driver driver = (Driver) _driverList.get(i); if (driver.acceptsURL(url)) return driver.getClass().getName(); } catch (Exception e) { log.log(Level.FINE, e.toString(), e); } } return null; }
public void contextDestroyed(ServletContextEvent event) { try { Introspector.flushCaches(); for (Enumeration e = DriverManager.getDrivers(); e.hasMoreElements(); ) { Driver driver = (Driver) e.nextElement(); if (driver.getClass().getClassLoader() == getClass().getClassLoader()) { DriverManager.deregisterDriver(driver); LOG.debug("deregistering driver: " + driver.getClass().getName()); } } } catch (Throwable e) { LOG.error("Failled to cleanup ClassLoader for webapp", e); } }
private Driver getUnderlyingDriver(String url) throws SQLException { if (url.startsWith(JDBC_SHARDS_PREFIX)) { Iterable<String> urls = getUnderlyingUrls(url); String underlyingUrl = Iterables.get(urls, 0); Enumeration e = DriverManager.getDrivers(); Driver d; while (e.hasMoreElements()) { d = (Driver) e.nextElement(); if (d.acceptsURL(underlyingUrl)) { return d; } } } return null; }
private void initDriverList() { try { Thread thread = Thread.currentThread(); ClassLoader loader = thread.getContextClassLoader(); Enumeration iter = loader.getResources("META-INF/services/java.sql.Driver"); while (iter.hasMoreElements()) { URL url = (URL) iter.nextElement(); ReadStream is = null; try { is = Vfs.lookup(url.toString()).openRead(); String filename; while ((filename = is.readLine()) != null) { int p = filename.indexOf('#'); if (p >= 0) filename = filename.substring(0, p); filename = filename.trim(); if (filename.length() == 0) continue; try { Class cl = Class.forName(filename, false, loader); Driver driver = null; if (Driver.class.isAssignableFrom(cl)) driver = (Driver) cl.newInstance(); if (driver != null) { log.fine(L.l("DatabaseManager adding driver '{0}'", driver.getClass().getName())); _driverList.add(driver); } } catch (Exception e) { log.log(Level.FINE, e.toString(), e); } } } catch (Exception e) { log.log(Level.FINE, e.toString(), e); } finally { if (is != null) is.close(); } } } catch (Exception e) { log.log(Level.FINE, e.toString(), e); } }
public Logger getParentLogger() throws SQLFeatureNotSupportedException { if (lastUnderlyingDriverRequested != null) { return lastUnderlyingDriverRequested.getParentLogger(); } else { throw new SQLFeatureNotSupportedException(); } }
/** * Get the minor version of the driver. This call will be delegated to the underlying driver that * is being spied upon (if there is no underlying driver found, then 0 will be returned.) * * @return the minor version of the JDBC driver. */ public int getMinorVersion() { if (lastUnderlyingDriverRequested == null) { return 0; } else { return lastUnderlyingDriverRequested.getMinorVersion(); } }
/** * 对于Weblogic连接池 * * @return boolean */ private boolean getWeblogicPoolConnection() { try { Driver myDriver = (Driver) (Class.forName("weblogic.jdbc.pool.Driver").newInstance()); /*weblogic的连接池重写了close()方法*/ con = myDriver.connect(JUrl.getJdbcUrl(), null); Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); stmt.execute("alter session set nls_date_format = 'YYYY-MM-DD HH24:MI:SS'"); stmt.close(); } catch (Exception ex) { System.out.println("$$$$$$$$WebLogicPool Connect Failed$$$$$"); return false; } return true; }
public Sql2oTest(Driver driverToRegister, String url, String user, String pass, String testName) { if (driverToRegister != null) { try { DriverManager.registerDriver(driverToRegister); } catch (SQLException e) { throw new RuntimeException( "could not register driver '" + driverToRegister.getClass().getName() + "'", e); } } this.sql2o = new Sql2o(url, user, pass); HashMap<String, String> defaultColumnMap = new HashMap<String, String>(); defaultColumnMap.put("ID", "id"); defaultColumnMap.put("NAME", "name"); defaultColumnMap.put("EMAIL", "email"); defaultColumnMap.put("TEXT", "text"); defaultColumnMap.put("ANUMBER", "aNumber"); defaultColumnMap.put("ALONGNUMBER", "aLongNumber"); sql2o.setDefaultColumnMappings(defaultColumnMap); this.url = url; this.user = user; this.pass = pass; if ("HyperSQL DB test".equals(testName)) { sql2o.createQuery("set database sql syntax MSS true").executeUpdate(); } }