<p>
Delegates the call to the wrapped data source, wraps the returned
connection and counts the connections returned.
</p>

@return  a database <code>Connection</code>
@throws  java.sql.SQLException
as a result of the delegation
179318
@Override
  public Connection getConnection() throws SQLException {
    return getConnection(
      new Callable<Connection>() {
        @Override
        public Connection call() throws SQLException {
          return MonitoringDataSource.this.original.getConnection();
        }
      },
      ".getConnection");
  }
135423
Connection getConnection() throws SQLException {
		if (connection == null) {
			connection = connectionSupplier.getConnection();
			initSavepoints(connection);
		}
		return connection;
	}
401901
public final Connection getConnection() throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException {
        String url = "jdbc:mysql://" + this.hostname + ":" + this.port + "/" + this.database + "?user=" + this.username + "&password="
                + this.password + "&autoReconnect=true" + "&failOverReadOnly=false&maxReconnects=3";
        DriverManager.registerDriver((Driver) Class.forName("com.mysql.jdbc.Driver").newInstance());
        return DriverManager.getConnection(url);
    }
530873
public Connection getConnection(String username, String password)
	throws SQLException {
		try {
			return this.multiDataSource.get(new UsernamePassword(username, password)).getConnection();
		} catch (ExecutionException e) {
			throw PoolUtil.generateSQLException("Unable to obtain connection", e);

		}
	}
259615
public static ResultSetResult wrapQuery(Connection connection, String sql,
			String[] selectionArgs) {
		return new ResultSetResult(query(connection, sql, selectionArgs));
	}
436855
@Override
  public final synchronized int getIdDatabase() {
    if (this.idDatabase == 0) {
      try {
        String query = "select count(*) as TOTALROWS from " + DatabaseInfo.class
          .getSimpleName().toUpperCase() + ";";
        Integer rowCount = evalIntegerResult(query, "TOTALROWS");
        if (rowCount != 1) {
          throw new ExceptionWithCode(ExceptionWithCode.CONFIGURATION_MISTAKE,
            "database_info_config_error");
        }
        query = "select DATABASEID from " + DatabaseInfo.class
          .getSimpleName().toUpperCase() + ";";
        Integer databaseId = evalIntegerResult(query, "DATABASEID");
        if (databaseId == null) {
          throw new ExceptionWithCode(ExceptionWithCode.CONFIGURATION_MISTAKE,
            "database_info_config_error");
        }
        this.idDatabase = databaseId;
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    }
    return this.idDatabase;
  }
1095663
private Connection getJdbcConnection() throws JspCoreException, SQLException {

        Connection conn = null;

        String url = getConnProperties().getUrl();
        String user = getConnProperties().getLoginUser();
        String passwd = getConnProperties().getLoginPasswd();
        String jndiName = getConnProperties().getJndiName();

        //System.out.println("***** Query.getJdbcConnection():  jndiname = " + jndiName);

        if (jndiName == null) { // use driver manager
            // load driver
            String dbDriver = (getConnProperties()).getDbDriver();
            try {
                Class.forName(dbDriver);
                conn = DriverManager.getConnection(url, user, passwd);
            } // try load driver
            catch (ClassNotFoundException e) {
                //com.ibm.ws.ffdc.FFDCFilter.processException(e, "com.ibm.ws.webcontainer.jsp.tsx.db.Query.getJdbcConnection", "174", this);
                throw new JspCoreException(JspConstants.InvalidDbDriver + dbDriver);
            } // catch
        } // if jndiname == null
        else { // use datasource
            DataSource ds;
            try {
                ds = getSingleton(jndiName);
            }
            catch (Throwable th) {
                //com.ibm.ws.ffdc.FFDCFilter.processException(th, "com.ibm.ws.webcontainer.jsp.tsx.db.Query.getJdbcConnection", "184", this);
                throw new JspCoreException(JspConstants.DatasourceException + th.getMessage());
            }
            conn = ds.getConnection(user, passwd);
        }

        return conn;
    }
753440
private Connection getConnection(final ICommandLine cl) throws SQLException, InstantiationException, IllegalAccessException,
            ClassNotFoundException {
        String database = DEFAULT_TABLE;
        if (cl.hasOption("database")) {
            database = cl.getOptionValue("database");
        }
        String hostname = DEFAULT_HOSTNAME;
        if (cl.hasOption("hostname") && !"".equals(cl.getOptionValue("hostname"))) {
            hostname = cl.getOptionValue("hostname");
        }
        String port = DEFAULT_PORT;
        if (cl.hasOption("port") && !"".equals(cl.getOptionValue("port"))) {
            port = cl.getOptionValue("port");
        }
        String password = "";
        if (cl.hasOption("password")) {
            password = cl.getOptionValue("password");
        }
        String username = "";
        if (cl.hasOption("logname")) {
            username = cl.getOptionValue("logname");
        }
        String timeout = DEFAULT_TIMEOUT;
        if (cl.getOptionValue("timeout") != null) {
            timeout = cl.getOptionValue("timeout");
        }
        Properties props = new Properties();
        props.setProperty("user", username);
        props.setProperty("password", password);
        props.setProperty("timeout", timeout);
        String url = "jdbc:postgresql://" + hostname + ":" + port + "/" + database;
        DriverManager.registerDriver((Driver) Class.forName("org.postgresql.Driver").newInstance());
        return DriverManager.getConnection(url, props);
    }
90280
boolean connect() throws SQLException {
    try {
      if (driver != null && driver.length() != 0) {
        Class.forName(driver);
      }
    } catch (ClassNotFoundException cnfe) {
      return sqlLine.error(cnfe);
    }

    boolean foundDriver = false;
    Driver theDriver = null;
    try {
      theDriver = DriverManager.getDriver(url);
      foundDriver = theDriver != null;
    } catch (Exception e) {
      // ignore
    }

    if (!foundDriver) {
      sqlLine.output(sqlLine.loc("autoloading-known-drivers", url));
      sqlLine.registerKnownDrivers();
      theDriver = DriverManager.getDriver(url);
    }

    try {
      close();
    } catch (Exception e) {
      return sqlLine.error(e);
    }

    // Avoid using DriverManager.getConnection(). It is a synchronized
    // method and thus holds the lock while making the connection.
    // Deadlock can occur if the driver's connection processing uses any
    // synchronized DriverManager methods.  One such example is the
    // RMI-JDBC driver, whose RJDriverServer.connect() method uses
    // DriverManager.getDriver(). Because RJDriverServer.connect runs in
    // a different thread (RMI) than the getConnection() caller (here),
    // this sequence will hang every time.
/*
          connection = DriverManager.getConnection (url, username, password);
*/
    // Instead, we use the driver instance to make the connection

    connection = theDriver.connect(url, info);
    meta = (DatabaseMetaData) Proxy.newProxyInstance(
        DatabaseMetaData.class.getClassLoader(),
        new Class[] {DatabaseMetaData.class},
        new DatabaseMetaDataHandler(connection.getMetaData()));
    try {
      sqlLine.debug(
          sqlLine.loc("connected",
              meta.getDatabaseProductName(),
              meta.getDatabaseProductVersion()));
    } catch (Exception e) {
      sqlLine.handleException(e);
    }

    try {
      sqlLine.debug(
          sqlLine.loc("driver",
              meta.getDriverName(),
              meta.getDriverVersion()));
    } catch (Exception e) {
      sqlLine.handleException(e);
    }

    try {
      connection.setAutoCommit(sqlLine.getOpts().getAutoCommit());
      sqlLine.autocommitStatus(connection);
    } catch (Exception e) {
      sqlLine.handleException(e);
    }

    try {
      // nothing is done off of this command beyond the handle so no
      // need to use the callback.
      sqlLine.getCommands().isolation("isolation: " + sqlLine.getOpts()
          .getIsolation(),
          new DispatchCallback());
      initSyntaxRule();
    } catch (Exception e) {
      sqlLine.handleException(e);
    }

    sqlLine.showWarnings();

    return true;
  }
627997
protected Connection obtainRawInternalConnection()
	throws SQLException {
		Connection result = null;

		DataSource datasourceBean = this.config.getDatasourceBean();
		String url = this.config.getJdbcUrl();
		String username = this.config.getUsername();
		String password = this.config.getPassword();
		Properties props = this.config.getDriverProperties();
		boolean externalAuth = this.config.isExternalAuth();
		if (externalAuth && 
				props == null){
			props = new Properties();
		}

		if (datasourceBean != null){
			return (username == null ? datasourceBean.getConnection() : datasourceBean.getConnection(username, password));
		}

		// just force the driver to init first
		if (!this.driverInitialized ){
			try{
				this.driverInitialized = true;
				if (props != null){
					result = DriverManager.getConnection(url, props);
				} else {
					result = DriverManager.getConnection(url, username, password);
				}
				result.close();
			}catch (SQLException t){
				// just force the driver to init first
				// See https://bugs.launchpad.net/bonecp/+bug/876476
			}
		}

		if (props != null){
			result = DriverManager.getConnection(url, props);
		} else { 
			result = DriverManager.getConnection(url, username, password);
		}
		// #ifdef JDK>6
		if (this.clientInfo != null){ // we take care of null'ing this in the constructor if jdk < 6
			result.setClientInfo(this.clientInfo);
		}
		// #endif JDK>6

		return result;
	}
543182
public Object[] call(Sql sql) throws SQLException {
		
		long start =  System.currentTimeMillis();
		
		if (sql.validate() == false) {
			return null;
		}
		
		List<Object> result = new ArrayList<Object>();
		
		Statement stmt = null;
		try {
			stmt = this.createStatment(conn, sql);
			if (stmt instanceof CallableStatement) {
				CallableStatement callStmt = (CallableStatement)stmt;
				callStmt.execute();
				List<Object> tmpResults = this.getProcedureOutValue(callStmt, sql);
				for (Object tmpResult : tmpResults) {
					if (tmpResult instanceof ResultSet) {
						result.add(getResultSet((ResultSet)tmpResult));
					} else {
						result.add(tmpResult);
					}
				}
			}
		} catch (SQLException e) {
			throw e;
		} finally {
			try {
				if (stmt != null && stmt.isClosed() == false) {
					stmt.close();
				}
			} catch (SQLException e) {
				logger.error(e.getMessage(), e);
			}
		}
		
		logger.debug(String.format("Execute %s used %d ms", sql.getSql(), System.currentTimeMillis() - start));
		
		return result.toArray();
	}
80994
public static SqlSession getSession() throws IOException {
		SqlSession session = (SqlSession) THREAD_SESSION.get();  
	    try {  
	        if (session == null) {  
	        	session = getSessionFactory().getSession();
	        	THREAD_SESSION.set(session);  
	        }  
	    } catch (Exception e) {  
	        throw new IOException(e);  
	    }  
	    return session;  
	}
39691
private Connection getPooledConnection() throws SQLException {
    PooledConnection pc = null;
    synchronized (lock) {
      if (available == null) {
        throw new PSQLException(GT.tr("DataSource has been closed."),
            PSQLState.CONNECTION_DOES_NOT_EXIST);
      }
      while (true) {
        if (!available.isEmpty()) {
          pc = available.pop();
          used.push(pc);
          break;
        }
        if (maxConnections == 0 || used.size() < maxConnections) {
          pc = source.getPooledConnection();
          used.push(pc);
          break;
        } else {
          try {
            // Wake up every second at a minimum
            lock.wait(1000L);
          } catch (InterruptedException e) {
          }
        }
      }
    }
    pc.addConnectionEventListener(connectionEventListener);
    return pc.getConnection();
  }
693958
public List<Connection> getConnections(final ConnectionMode connectionMode, final String dataSourceName, final int connectionSize) throws SQLException {
        return getConnections(connectionMode, dataSourceName, connectionSize, TransactionType.LOCAL);
    }
47059
protected ConnectionWrapper createConnection(Transaction tx) throws SQLException {
        final XAConnection xaConn = xaDataSource.getXAConnection();
        final Connection conn = xaConn.getConnection();
        final ConnectionWrapper wrapper = createTransactionalConnectionWrapper(xaConn, conn, tx);
        if (logger.isDebugEnabled()) {
            logger.debug("Created physical connection: tx={}, conn={}", tx, conn);
        }
        return wrapper;
    }
855217
@Override
  public Connection getConnection() throws SQLException {

    this.dbMetrics.markDBConnection();
    final long startMs = System.currentTimeMillis();
    Connection connection = null;
    int retryAttempt = 1;
    while (retryAttempt < AzDBUtil.MAX_DB_RETRY_COUNT) {
      try {
        /**
         * when DB connection could not be fetched (e.g., network issue), or connection can not be validated,
         * {@link BasicDataSource} throws a SQL Exception. {@link BasicDataSource#dataSource} will be reset to null.
         * createDataSource() will create a new dataSource.
         * Every Attempt generates a thread-hanging-time, about 75 seconds, which is hard coded, and can not be changed.
         */
        connection = createDataSource().getConnection();

        /**
         * If connection is null or connection is read only, retry to find available connection.
         * When DB fails over from master to slave, master is set to read-only mode. We must keep
         * finding correct data source and sql connection.
         */
        if (connection == null || isReadOnly(connection)) {
          throw new SQLException("Failed to find DB connection Or connection is read only. ");
        } else {

          // Evalaute how long it takes to get DB Connection.
          this.dbMetrics.setDBConnectionTime(System.currentTimeMillis() - startMs);
          return connection;
        }
      } catch (final SQLException ex) {

        /**
         * invalidate connection and reconstruct it later. if remote IP address is not reachable,
         * it will get hang for a while and throw exception.
         */
        this.dbMetrics.markDBFailConnection();
        try {
          invalidateConnection(connection);
        } catch (final Exception e) {
          logger.error( "can not invalidate connection.", e);
        }
        logger.error( "Failed to find write-enabled DB connection. Wait 15 seconds and retry."
            + " No.Attempt = " + retryAttempt, ex);
        /**
         * When database is completed down, DB connection fails to be fetched immediately. So we need
         * to sleep 15 seconds for retry.
         */
        sleep(1000L * 15);
        retryAttempt++;
      }
    }
    return connection;
  }
767936
public static Connection getConnection() {
        Connection connection = tl_conn.get();
        try {
            // 若tl.get()返回不是null说明当前线程有事务连接，直接返回事务连接
            if (connection != null) {
                return connection;
            }
            // 若为null则从连接池里返回一个连接
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return connection;
    }