Example #1
0
  public static List<Map<String, Object>> executeQuery(
      Connection conn, String sql, List<Object> parameters) throws SQLException {
    List<Map<String, Object>> rows = new ArrayList<Map<String, Object>>();

    PreparedStatement stmt = null;
    ResultSet rs = null;
    try {
      stmt = conn.prepareStatement(sql);

      setParameters(stmt, parameters);

      rs = stmt.executeQuery();

      ResultSetMetaData rsMeta = rs.getMetaData();

      while (rs.next()) {
        Map<String, Object> row = new LinkedHashMap<String, Object>();

        for (int i = 0, size = rsMeta.getColumnCount(); i < size; ++i) {
          String columName = rsMeta.getColumnLabel(i + 1);
          Object value = rs.getObject(i + 1);
          row.put(columName, value);
        }

        rows.add(row);
      }
    } finally {
      JdbcUtils.close(rs);
      JdbcUtils.close(stmt);
    }

    return rows;
  }
Example #2
0
  public void test_o() throws Exception {
    {
      Connection[] connections = new Connection[3];
      for (int i = 0; i < connections.length; ++i) {
        connections[i] = dataSource.getConnection();
      }

      for (int i = 0; i < connections.length; ++i) {
        Statement stmt = connections[i].createStatement();
        ResultSet rs = stmt.executeQuery("select now()");
        JdbcUtils.printResultSet(rs);
        rs.close();
        stmt.close();
      }

      for (int i = 0; i < connections.length; ++i) {
        connections[i].close();
      }
    }

    Thread.sleep(1000 * 60 * 60 * 6); // 6 hours
    Connection conn = dataSource.getConnection();

    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("select now()");
    JdbcUtils.printResultSet(rs);
    rs.close();
    stmt.close();

    conn.close();
  }
Example #3
0
  public boolean isValidConnection(DruidDataSource dataSource, Connection conn) {
    Statement stmt = null;
    ResultSet rs = null;
    try {
      stmt = conn.createStatement();
      stmt.setQueryTimeout(queryTimeoutSeconds);
      rs = stmt.executeQuery(getValidateSql());
      if (!rs.next()) {
        return false;
      }

      String status = rs.getString(1);

      if ("on".equalsIgnoreCase(status)) {
        return true;
      } else {
        return false;
      }
    } catch (Exception ex) {
      LOG.error("check datasource valid errror", ex);
      return false;
    } finally {
      JdbcUtils.close(rs);
      JdbcUtils.close(stmt);
    }
  }
  public boolean isValidConnection(
      Connection conn, String valiateQuery, int validationQueryTimeout) {
    try {
      if (conn.isClosed()) {
        return false;
      }
    } catch (SQLException ex) {
      // skip
      return false;
    }

    if (valiateQuery == null) {
      return true;
    }

    try {
      if (conn instanceof DruidPooledConnection) {
        conn = ((DruidPooledConnection) conn).getConnection();
      }

      if (conn instanceof ConnectionProxy) {
        conn = ((ConnectionProxy) conn).getRawObject();
      }

      // unwrap
      if (clazz != null && clazz.isAssignableFrom(conn.getClass())) {
        Integer status = (Integer) ping.invoke(conn, params);

        // Error
        if (status.intValue() < 0) {
          return false;
        }

        return true;
      }

      Statement stmt = null;
      ResultSet rs = null;
      try {
        stmt = conn.createStatement();
        rs = stmt.executeQuery(valiateQuery);
        return true;
      } catch (SQLException e) {
        return false;
      } catch (Exception e) {
        LOG.warn("Unexpected error in ping", e);
        return false;
      } finally {
        JdbcUtils.close(rs);
        JdbcUtils.close(stmt);
      }
    } catch (Exception e) {
      LOG.warn("Unexpected error in pingDatabase", e);
    }

    // OK
    return true;
  }
Example #5
0
 public DataSourceProxyImpl(Driver rawDriver, DataSourceProxyConfig config) {
   super();
   this.rawDriver = rawDriver;
   this.config = config;
   this.dbType = JdbcUtils.getDbType(config.getRawUrl(), config.getRawDriverClassName());
   this.dataSourceStat = new JdbcDataSourceStat(config.getName(), config.getUrl(), dbType);
 }
Example #6
0
  static {
    try {
      ClassLoader ctxClassLoader = Thread.currentThread().getContextClassLoader();
      if (ctxClassLoader != null) {
        for (Enumeration<URL> e = ctxClassLoader.getResources("META-INF/druid-driver.properties");
            e.hasMoreElements(); ) {
          URL url = e.nextElement();

          Properties property = new Properties();

          InputStream is = null;
          try {
            is = url.openStream();
            property.load(is);
          } finally {
            JdbcUtils.close(is);
          }

          DRIVER_URL_MAPPING.putAll(property);
        }
      }
    } catch (Exception e) {
      LOG.error("load druid-driver.properties error", e);
    }
  }
  public void reset() throws SQLException {
    // reset default settings
    if (underlyingReadOnly != defaultReadOnly) {
      conn.setReadOnly(defaultReadOnly);
      underlyingReadOnly = defaultReadOnly;
    }

    if (underlyingHoldability != defaultHoldability) {
      conn.setHoldability(defaultHoldability);
      underlyingHoldability = defaultHoldability;
    }

    if (underlyingTransactionIsolation != defaultTransactionIsolation) {
      conn.setTransactionIsolation(defaultTransactionIsolation);
      underlyingTransactionIsolation = defaultTransactionIsolation;
    }

    if (underlyingAutoCommit != defaultAutoCommit) {
      conn.setAutoCommit(defaultAutoCommit);
      underlyingAutoCommit = defaultAutoCommit;
    }

    connectionEventListeners.clear();
    statementEventListeners.clear();

    for (Object item : statementTrace.toArray()) {
      Statement stmt = (Statement) item;
      JdbcUtils.close(stmt);
    }
    statementTrace.clear();

    conn.clearWarnings();
  }
Example #8
0
  public void exec_test(String resource) throws Exception {
    //        System.out.println(resource);
    InputStream is = null;

    is = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource);
    Reader reader = new InputStreamReader(is, "UTF-8");
    String input = Utils.read(reader);
    JdbcUtils.close(reader);
    String[] items = input.split("---------------------------");
    String sql = items[0].trim();
    String expect = items[1].trim();

    OdpsStatementParser parser = new OdpsStatementParser(sql);
    List<SQLStatement> statementList = parser.parseStatementList();
    SQLStatement stmt = statementList.get(0);

    Assert.assertEquals(1, statementList.size());

    SchemaStatVisitor visitor = new OdpsSchemaStatVisitor();
    stmt.accept(visitor);

    //        System.out.println(sql);
    //        System.out.println("Tables : " + visitor.getTables());
    //        System.out.println("fields : " + visitor.getColumns());
    //
    //        System.out.println();
    //        System.out.println("---------------------------");
    //        System.out.println(SQLUtils.toOdpsString(stmt));
  }
 public OracleValidConnectionChecker() {
   try {
     clazz = JdbcUtils.loadDriverClass("oracle.jdbc.driver.OracleConnection");
     if (clazz != null) {
       ping = clazz.getMethod("pingDatabase", new Class[] {Integer.TYPE});
     } else {
       ping = null;
     }
   } catch (Exception e) {
     throw new RuntimeException("Unable to resolve pingDatabase method:", e);
   }
 }
  public void test_0() throws Exception {
    //        ResultSet rs = conn.getMetaData().getTables(null, null, null, null);
    //        JdbcUtils.printResultSet(rs);

    String sql = "select benchmark( 1, sha1( 'test' ) )";
    Statement stmt = conn.createStatement();

    ResultSet rs = stmt.executeQuery(sql);
    JdbcUtils.printResultSet(rs);

    stmt.close();
  }
Example #11
0
  public static void execute(Connection conn, String sql, List<Object> parameters)
      throws SQLException {
    PreparedStatement stmt = null;

    try {
      stmt = conn.prepareStatement(sql);

      setParameters(stmt, parameters);

      stmt.executeUpdate();
    } finally {
      JdbcUtils.close(stmt);
    }
  }
Example #12
0
  public static DataSourceProxyConfig parseConfig(String url, Properties info) throws SQLException {
    String restUrl = url.substring(DEFAULT_PREFIX.length());

    DataSourceProxyConfig config = new DataSourceProxyConfig();

    if (restUrl.startsWith(DRIVER_PREFIX)) {
      int pos = restUrl.indexOf(':', DRIVER_PREFIX.length());
      String driverText = restUrl.substring(DRIVER_PREFIX.length(), pos);
      if (driverText.length() > 0) {
        config.setRawDriverClassName(driverText.trim());
      }
      restUrl = restUrl.substring(pos + 1);
    }

    if (restUrl.startsWith(FILTERS_PREFIX)) {
      int pos = restUrl.indexOf(':', FILTERS_PREFIX.length());
      String filtersText = restUrl.substring(FILTERS_PREFIX.length(), pos);
      for (String filterItem : filtersText.split(",")) {
        FilterManager.loadFilter(config.getFilters(), filterItem);
      }
      restUrl = restUrl.substring(pos + 1);
    }

    if (restUrl.startsWith(NAME_PREFIX)) {
      int pos = restUrl.indexOf(':', NAME_PREFIX.length());
      String name = restUrl.substring(NAME_PREFIX.length(), pos);
      config.setName(name);
      restUrl = restUrl.substring(pos + 1);
    }

    if (restUrl.startsWith(JMX_PREFIX)) {
      int pos = restUrl.indexOf(':', JMX_PREFIX.length());
      String jmxOption = restUrl.substring(JMX_PREFIX.length(), pos);
      config.setJmxOption(jmxOption);
      restUrl = restUrl.substring(pos + 1);
    }

    String rawUrl = restUrl;
    config.setRawUrl(rawUrl);

    if (config.getRawDriverClassName() == null) {
      String rawDriverClassname = JdbcUtils.getDriverClassName(rawUrl);
      config.setRawDriverClassName(rawDriverClassname);
    }

    config.setUrl(url);
    return config;
  }
Example #13
0
  public Driver createDriver(String className) throws SQLException {
    Class<?> rawDriverClass = JdbcUtils.loadDriverClass(className);

    if (rawDriverClass == null) {
      throw new SQLException("jdbc-driver's class not found. '" + className + "'");
    }

    Driver rawDriver;
    try {
      rawDriver = (Driver) rawDriverClass.newInstance();
    } catch (InstantiationException e) {
      throw new SQLException("create driver instance error, driver className '" + className + "'");
    } catch (IllegalAccessException e) {
      throw new SQLException("create driver instance error, driver className '" + className + "'");
    }

    return rawDriver;
  }
 protected void tearDown() throws Exception {
   JdbcUtils.close(dataSource);
 }
  public boolean isValidConnection(
      Connection conn, String validateQuery, int validationQueryTimeout) {
    try {
      if (conn.isClosed()) {
        return false;
      }
    } catch (SQLException ex) {
      // skip
      return false;
    }

    if (usePingMethod) {
      if (conn instanceof DruidPooledConnection) {
        conn = ((DruidPooledConnection) conn).getConnection();
      }

      if (conn instanceof ConnectionProxy) {
        conn = ((ConnectionProxy) conn).getRawObject();
      }

      if (clazz.isAssignableFrom(conn.getClass())) {
        if (validationQueryTimeout < 0) {
          validationQueryTimeout = DEFAULT_VALIDATION_QUERY_TIMEOUT;
        }

        try {
          ping.invoke(conn, true, validationQueryTimeout);
          return true;
        } catch (InvocationTargetException e) {
          Throwable cause = e.getCause();
          if (cause instanceof SQLException) {
            return false;
          }

          LOG.warn("Unexpected error in ping", e);
          return false;
        } catch (Exception e) {
          LOG.warn("Unexpected error in ping", e);
          return false;
        }
      }
    }

    Statement stmt = null;
    ResultSet rs = null;
    try {
      stmt = conn.createStatement();
      if (validationQueryTimeout > 0) {
        stmt.setQueryTimeout(validationQueryTimeout);
      }
      rs = stmt.executeQuery(validateQuery);
      return true;
    } catch (SQLException e) {
      return false;
    } catch (Exception e) {
      LOG.warn("Unexpected error in ping", e);
      return false;
    } finally {
      JdbcUtils.close(rs);
      JdbcUtils.close(stmt);
    }
  }
 @Override
 protected void tearDown() throws Exception {
   JdbcUtils.close(dataSource);
   Assert.assertEquals(0, DruidDataSourceStatManager.getInstance().getDataSourceList().size());
 }
  protected void tearDown() throws Exception {
    JdbcUtils.close(dataSource);

    Assert.assertEquals(0, JdbcStatManager.getInstance().getSqlList().size());
  }