コード例 #1
0
 /** 统计数据源的一些信息 */
 public void info() {
   if (closed) {
     Log.w(tag, "DataSource is closed.");
     return;
   }
   pool.staticsInfo();
 }
コード例 #2
0
  /**
   * 创建数据源
   *
   * @return 创建好的数据源
   * @throws SQLException
   */
  protected DataSource createDataSource() throws SQLException {
    if (closed) throw new SQLException("The DataSource is closed.");

    if (dataSource != null) {
      return dataSource;
    }

    synchronized (this) {
      if (dataSource != null) return dataSource;

      Driver driverToUse = this.driver;
      if (driverToUse == null) {
        Class<?> driverFromCCL = null;
        if (driverClassName != null) {
          try {
            driverFromCCL = Class.forName(driverClassName);
          } catch (ClassNotFoundException e) {
            Log.e(e, tag, "Cannot load JDBC driver class " + driverClassName);
            throw new SQLException(e);
          }
        }

        try {
          if (driverFromCCL == null) {
            driverToUse = DriverManager.getDriver(url);
          } else {
            driverToUse = (Driver) driverFromCCL.newInstance();
            if (!driverToUse.acceptsURL(url)) {
              throw new SQLException("No suitable driver", "08001");
            }
          }
        } catch (Exception e) {
          Log.e(
              e,
              tag,
              "Cannot create JDBC driver of class %s for connection url %s",
              driverClassName != null ? driverClassName : "",
              url);
          throw new SQLException(e);
        }
        this.driver = driverToUse;
      }

      String user = userName;
      if (user != null) {
        props.put("user", user);
      } else {
        Log.w(tag, "DataSource configured without a 'username'");
      }

      String pwd = password;
      if (pwd != null) {
        props.put("password", pwd);
      } else {
        Log.w(tag, "DataSource configured without a 'password'");
      }

      try {
        connectionFactory = new JdbcConnectionFactory(driver, url, props);
        jdbcConnectionValidator = new JdbcConnectionValidator();
        pool =
            new BoundedBlockingPool<>(maxConnections, jdbcConnectionValidator, connectionFactory);
        dataSource = new PooledDataSource<>(pool);
        dataSource.setLogWriter(logWriter);
      } catch (SQLException e) {
        Log.e(e, tag, "Cannot create a datasource.");
        throw new SQLException(e);
      }
      return dataSource;
    }
  }