$DB->Connect('USER ID=sa;PASSWORD=pwd;SERVER=mangrove;DATABASE=ai',false,false,'SQLOLEDB');
356677
function _connect($argHostname, $argUsername, $argPassword,$argDBorProvider, $argProvider= '')
	{
	// two modes
	//	-	if $argProvider is empty, we assume that $argDBorProvider holds provider -- this is for backward compat
	//	- 	if $argProvider is not empty, then $argDBorProvider holds db


		 if ($argProvider) {
		 	$argDatabasename = $argDBorProvider;
		 } else {
		 	$argDatabasename = '';
		 	if ($argDBorProvider) $argProvider = $argDBorProvider;
			else if (stripos($argHostname,'PROVIDER') === false) /* full conn string is not in $argHostname */
				$argProvider = 'MSDASQL';
		}


		try {
		$u = 'UID';
		$p = 'PWD';

		if (!empty($this->charPage))
			$dbc = new COM('ADODB.Connection',null,$this->charPage);
		else
			$dbc = new COM('ADODB.Connection');

		if (! $dbc) return false;

		/* special support if provider is mssql or access */
		if ($argProvider=='mssql') {
			$u = 'User Id';  //User parameter name for OLEDB
			$p = 'Password';
			$argProvider = "SQLOLEDB"; // SQL Server Provider

			// not yet
			//if ($argDatabasename) $argHostname .= ";Initial Catalog=$argDatabasename";

			//use trusted conection for SQL if username not specified
			if (!$argUsername) $argHostname .= ";Trusted_Connection=Yes";
		} else if ($argProvider=='access')
			$argProvider = "Microsoft.Jet.OLEDB.4.0"; // Microsoft Jet Provider

		if ($argProvider) $dbc->Provider = $argProvider;

		if ($argProvider) $argHostname = "PROVIDER=$argProvider;DRIVER={SQL Server};SERVER=$argHostname";


		if ($argDatabasename) $argHostname .= ";DATABASE=$argDatabasename";
		if ($argUsername) $argHostname .= ";$u=$argUsername";
		if ($argPassword)$argHostname .= ";$p=$argPassword";

		if ($this->debug) ADOConnection::outp( "Host=".$argHostname."<BR>\n version=$dbc->version");
		// @ added below for php 4.0.1 and earlier
		@$dbc->Open((string) $argHostname);

		$this->_connectionID = $dbc;

		$dbc->CursorLocation = $this->_cursor_location;
		return  $dbc->State > 0;
		} catch (exception $e) {
			if ($this->debug) echo "<pre>",$argHostname,"\n",$e,"</pre>\n";
		}

		return false;
	}
455779
private function connect()
    {
        try {
            $this->db = new \PDO(
                $this->dbOptions['dsn'],
                $this->dbOptions['username'],
                $this->dbOptions['password'],
                $this->dbOptions['driver_options']
            );

        } catch (\Exception $e) {
            //Change to true to debug database connection
            if ($this->dbOptions['debug']) {
                // For debug purpose, shows all connection details
                throw $e;
            } else {
                // Hide connection details.
                throw new \PDOException("Could not connect to database, hiding connection details.");
            }
        }
        $this->db->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_OBJ);
    }
799233
function _connect($argDSN, $argUsername, $argPassword, $argDatabasename)
	{
		global $php_errormsg;

		if (!function_exists('db2_connect')) {
			ADOConnection::outp("Warning: The old ODBC based DB2 driver has been renamed 'odbc_db2'. This ADOdb driver calls PHP's native db2 extension which is not installed.");
			return null;
		}
		// This needs to be set before the connect().
		// Replaces the odbc_binmode() call that was in Execute()
		ini_set('ibm_db2.binmode', $this->binmode);

		if ($argDatabasename && empty($argDSN)) {

			if (stripos($argDatabasename,'UID=') && stripos($argDatabasename,'PWD=')) $this->_connectionID = db2_connect($argDatabasename,null,null);
			else $this->_connectionID = db2_connect($argDatabasename,$argUsername,$argPassword);
		} else {
			if ($argDatabasename) $schema = $argDatabasename;
			if (stripos($argDSN,'UID=') && stripos($argDSN,'PWD=')) $this->_connectionID = db2_connect($argDSN,null,null);
			else $this->_connectionID = db2_connect($argDSN,$argUsername,$argPassword);
		}
		if (isset($php_errormsg)) $php_errormsg = '';

		// For db2_connect(), there is an optional 4th arg.  If present, it must be
		// an array of valid options.  So far, we don't use them.

		$this->_errorMsg = @db2_conn_errormsg();
		if (isset($this->connectStmt)) $this->Execute($this->connectStmt);

		if ($this->_connectionID && isset($schema)) $this->Execute("SET SCHEMA=$schema");
		return $this->_connectionID != false;
	}
395287
private static function createConnection()
    {
        // Validate if configuration has enough details.
        $driver = Configuration::get('database_driver');

        // Make DSN and options
        $dsn = "";
        $options = Configuration::get('database-options');
        $options = !is_array($options) ? array() : $options;

        $user = null;
        $password = null;

        if ($driver === 'pdo_sqlite') {
            // We will ignore this for now, as it's not tested with SQLite yet!
            // @codeCoverageIgnoreStart
            $path = Configuration::get('database_path');

            if (! $path || ! file_exists($path)) {
                throw new \Exception("SQLite Database File doesn't exists or not configured! '".$path."'");
            }

            $dsn = "sqlite:" . $path;
            // @codeCoverageIgnoreEnd
        }else if ($driver === 'pdo_mysql') {
            $host = Configuration::get('database_host');
            $database = Configuration::get('database_db');
            $user = Configuration::get('database_user');
            $password = Configuration::get('database_password');

            $port = Configuration::get('database_port');
            $port = !is_int($port) ? 3306 : $port;

            $encoding = Configuration::get('database_encoding');
            $encoding = $encoding == null ? 'utf8' : $encoding;

            if (is_null($host) || is_null($database) || is_null($user) || is_null($password)) {
                throw new \Exception("Please configure the ORM first. We can't get a connection now!");
            }

            $dsn = "mysql:host=" . $host . ";port=" . $port . ";dbname=" . $database . ";charset=" . $encoding;
        }else{
            throw new \Exception("Please configure the ORM first. We can't get a connection now! No driver given!");
        }

        // Make connection
        self::$connection = new \PDO($dsn, $user, $password, $options);
    }
853411
public function _connect()
    {
        $siteINI = eZINI::instance( 'site.ini' );
        // DB Connection setup
        // This part is not actually required since _connect will only be called
        // once, but it is useful to run the unit tests. So be it.
        // @todo refactor this using eZINI::setVariable in unit tests
        if ( parent::$dbparams === null )
        {
            $fileINI = eZINI::instance( 'file.ini' );

            parent::$dbparams = array();
            parent::$dbparams['host']       = $fileINI->variable( 'eZDFSClusteringSettings', 'DBHost' );
            $dbPort = $fileINI->variable( 'eZDFSClusteringSettings', 'DBPort' );
            parent::$dbparams['port']       = $dbPort !== '' ? $dbPort : null;
            parent::$dbparams['socket']     = $fileINI->variable( 'eZDFSClusteringSettings', 'DBSocket' );
            parent::$dbparams['dbname']     = $fileINI->variable( 'eZDFSClusteringSettings', 'DBName' );
            parent::$dbparams['user']       = $fileINI->variable( 'eZDFSClusteringSettings', 'DBUser' );
            parent::$dbparams['pass']       = $fileINI->variable( 'eZDFSClusteringSettings', 'DBPassword' );

            parent::$dbparams['max_connect_tries'] = $fileINI->variable( 'eZDFSClusteringSettings', 'DBConnectRetries' );
            parent::$dbparams['max_execute_tries'] = $fileINI->variable( 'eZDFSClusteringSettings', 'DBExecuteRetries' );

            parent::$dbparams['sql_output'] = $siteINI->variable( "DatabaseSettings", "SQLOutput" ) == "enabled";

            parent::$dbparams['cache_generation_timeout'] = $siteINI->variable( "ContentSettings", "CacheGenerationTimeout" );
        }

        $serverString = parent::$dbparams['host'];
        if ( parent::$dbparams['socket'] )
            $serverString .= ':' . parent::$dbparams['socket'];
        elseif ( parent::$dbparams['port'] )
            $serverString .= ':' . parent::$dbparams['port'];

        $maxTries = parent::$dbparams['max_connect_tries'];
        $tries = 0;
        eZPerfLogger::accumulatorStart( 'mysql_cluster_connect', 'MySQL Cluster', 'Cluster database connection' );
        while ( $tries < $maxTries )
        {
            if ( $this->db = mysqli_connect( parent::$dbparams['host'], parent::$dbparams['user'], parent::$dbparams['pass'], parent::$dbparams['dbname'], parent::$dbparams['port'] ) )
                break;
            ++$tries;
        }
        eZPerfLogger::accumulatorStop( 'mysql_cluster_connect' );
        if ( !$this->db )
        {
            throw new eZClusterHandlerDBNoConnectionException(
                $serverString,
                self::$dbparams['user'],
                self::$dbparams['pass'],
                'Error ' . mysqli_connect_errno() . ': ' . mysqli_connect_error()
            );
        }

        /*if ( !mysql_select_db( parent::$dbparams['dbname'], $this->db ) )
           throw new eZClusterHandlerDBNoDatabaseException( parent::$dbparams['dbname'] );*/

        // DFS setup
        if ( $this->dfsbackend === null )
        {
            $this->dfsbackend = new eZDFSFileHandlerTracing47DFSBackend();
        }

        $charset = trim( $siteINI->variable( 'DatabaseSettings', 'Charset' ) );
        if ( $charset === '' )
        {
            $charset = eZTextCodec::internalCharset();
        }

        if ( $charset )
        {
            if ( !mysqli_set_charset( $this->db, eZMySQLCharset::mapTo( $charset ) ) )
            {
                $this->_fail( "Failed to set Database charset to $charset." );
            }
        }
    }
857376
private function connect () {
    $connectionString = "host=".$this->server." port=".$this->port." dbname=".$this->db." user=".$this->user." password=".$this->password;
    $this->handler = pg_connect ($connectionString);
  }
663425
public function connect()
    {
        $options = & $this->options;
        
        try {
            if (!$this->connection && !@$this->connection->sqlstate) {
                if (isset($options['dsn'])) {
                    $this->connection = new \PDO($options['dsn']);
                } else {
                    if ($options['dbtype'] === 'sqlite') {
                        $this->dsn = $options['dsn'] = $options['dbtype'] . ':' . $options['database'];
                        $this->connection = new \PDO($options['dsn']);
                    } else {
                        if (!isset($options['host']) || !isset($options['username']) || !isset($options['password'])) {
                            throw new Exception('Error: The proper database credentials were not passed.');
                        }
                        if ($options['dbtype'] === 'sqlsrv') {
                            $options['dsn'] = $options['dbtype'] . ':Server=' . $options['host'] . ';Database=' . $options['database'];
                        } else {
                            $options['dsn'] = $options['dbtype'] . ':host=' . $options['host'] . ';dbname=' . $options['database'];
                        }
                        $this->dsn = & $options['dsn'];
                        $this->connection = new \PDO($this->dsn, $options['username'], $options['password']);
                    }
                }
            }
        } catch (\PDOException $e) {
            throw new Exception('Error: Could not connect to database. ' . $e->getMessage());
        }
    }
822944
private function tryConnect(): void
    {
        $config = $this->getConfig();

        $pdoConfig = [
          PDO::ATTR_EMULATE_PREPARES => false,
          PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
          PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ];

        if (isset($config['adapter_options'])) {
            foreach ($config['adapter_options'] as $key => $value) {
                $pdoConfig[$key] = $value;
            }
        }

        if (isset($config['path'])) {
            $path = $config['path'];
            if (substr($path, 0, 8) == 'storage:') {
                $path = Application::getStoragePath(substr($path, 8));
            }
        } else {
            $path = Application::getStoragePath('data/database.sqlite');
        }

        $directory = dirname($path);
        if (!is_dir($directory)) {
            Directory::mkdir($directory, 0755);
        }

        $this->pdo = new PDO('sqlite:' . $path);
        foreach ($pdoConfig as $key => $value) {
            $this->pdo->setAttribute($key, $value);
        }

        // create needed function(s)
        $this->pdo->sqliteCreateFunction('ILIKE', function ($mask, $value) {
            $mask = str_replace(['%', '_'], ['.*?', '.'], preg_quote($mask, '/'));
            $mask = "/^$mask$/ui";
            return preg_match($mask, $value);
        }, 2);
    }
581786
public void setupDBConnection() throws DBException
    {
        String strURL = this.getProperty(SQLParams.JDBC_URL_PARAM);
        if ((strURL == null) || (strURL.length() == 0))
            strURL = this.getProperty(SQLParams.DEFAULT_JDBC_URL_PARAM);    // Default
        String strServer = this.getProperty(SQLParams.DB_SERVER_PARAM);
        if ((strServer == null) || (strServer.length() == 0))
            strServer = this.getProperty(SQLParams.DEFAULT_DB_SERVER_PARAM);    // Default
        if ((strServer == null) || (strServer.length() == 0))
            strServer = "localhost"; //this.getProperty(DBParams.SERVER);    // ??       
        String strDatabaseName = this.getDatabaseName(true);
        strURL = Utility.replace(strURL, "${dbname}", strDatabaseName);
        if (strServer != null)
            strURL = Utility.replace(strURL, "${dbserver}", strServer);
        if (strURL.contains("${user.home}"))
        {
            try {
                strURL = Utility.replace(strURL, "${user.home}", System.getProperty("user.home"));
            } catch (SecurityException e) {
                strURL = Utility.replace(strURL, "${user.home}", "");
            }
        }
        String strUsername = this.getProperty(SQLParams.USERNAME_PARAM);
        if ((strUsername == null) || (strUsername.length() == 0))
            strUsername = this.getProperty(SQLParams.DEFAULT_USERNAME_PARAM); // Default
        String strPassword = this.getProperty(SQLParams.PASSWORD_PARAM);
        if ((strPassword == null) || (strPassword.length() == 0))
            strPassword = this.getProperty(SQLParams.DEFAULT_PASSWORD_PARAM); // Default
        // Open the database for non-exclusive access
        try   {
            Utility.getLogger().info("Connecting: " + strURL + " User: " + strUsername);
            m_JDBCConnection = DriverManager.getConnection(strURL, strUsername, strPassword);
            Utility.getLogger().info("Connection okay: " + (m_JDBCConnection != null));
        }
        catch (SQLException e)
        {
            DBException ex = this.convertError(e);    // Probably "DB Not found"
            if ((ex.getErrorCode() == DBConstants.DB_NOT_FOUND)
                && (!DBConstants.FALSE.equalsIgnoreCase(this.getProperty(DBConstants.CREATE_DB_IF_NOT_FOUND)))
                    && (DBConstants.TRUE.equals(this.getProperty(SQLParams.CREATE_DATABASE_SUPPORTED))))
            {
                if (this.create(strDatabaseName)) // Database not found, create it.
                    return;     // Success
            	e.printStackTrace();
            }
            if (ex.getErrorCode() != DBConstants.DB_NOT_FOUND)
            	e.printStackTrace();	// Ignore if create is turned off
            throw ex;
        }
        catch (java.lang.Exception ex)
        {
            ex.printStackTrace();
            Debug.print(ex, "Error on open db");
            System.exit(0);
        }
    }
1011185
public function connect() {
        $adapter = Zend_Db_Table::getDefaultAdapter();
        if (!$adapter) {
            Garp_Cli::errorOut('No database adapter found');
            return false;
        }
        $config = $adapter->getConfig();
        $params = array(
            '-u' . escapeshellarg($config['username']),
            '-p' . escapeshellarg($config['password']),
            '-h' . escapeshellarg($config['host']),
            ' ' . escapeshellarg($config['dbname'])
        );
        $cmd = 'mysql ' . implode(' ', $params);
        $process = proc_open($cmd, array(0 => STDIN, 1 => STDOUT, 2 => STDERR), $pipes);
        $proc_status = proc_get_status($process);
        $exit_code = proc_close($process);
        return ($proc_status["running"] ? $exit_code : $proc_status["exitcode"] ) == 0;
    }
1348314
function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
	{
		if (!function_exists('sqlsrv_connect')) return null;
		$connectionInfo = $this->connectionInfo;
		$connectionInfo["Database"]=$argDatabasename;
		$connectionInfo["UID"]=$argUsername;
		$connectionInfo["PWD"]=$argPassword;
		
		foreach ($this->connectionParameters as $parameter=>$value)
		    $connectionInfo[$parameter] = $value;
		
		if ($this->debug) ADOConnection::outp("<hr>connecting... hostname: $argHostname params: ".var_export($connectionInfo,true));
		//if ($this->debug) ADOConnection::outp("<hr>_connectionID before: ".serialize($this->_connectionID));
		if(!($this->_connectionID = sqlsrv_connect($argHostname,$connectionInfo))) {
			if ($this->debug) ADOConnection::outp( "<hr><b>errors</b>: ".print_r( sqlsrv_errors(), true));
			return false;
		}
		//if ($this->debug) ADOConnection::outp(" _connectionID after: ".serialize($this->_connectionID));
		//if ($this->debug) ADOConnection::outp("<hr>defined functions: <pre>".var_export(get_defined_functions(),true)."</pre>");
		return true;
	}
1055467
def _get_db_connect(dbSystem,db,user,password):
    
    if dbSystem=='SYBASE':
        import Sybase    
        try:
            dbh = Sybase.connect(dbSystem,
                                 user,
                                 password,
                                 database=db )
        except:
            dbh=None
    elif dbSystem=='MYSQL':
        import MySQLdb
        try:
            dbh = MySQLdb.connect(user=user,
                                  passwd=password,
                                  db=db ,
                                  host='gimli')
        except:
            dbh=None
            
    return dbh
1124337
private function connect()
    {
        $port = isset($this->_args['port']) && $this->_args['port'] ? $this->_args['port'] : 3306;
        $dsn = "mysql:host={$this->_args['host']};port={$port};dbname={$this->_args['dbname']}";
        $username = $this->_args['username'];
        $password = $this->_args['password'];

        // TODO: Move to use the follow: PDO::ATTR_EMULATE_PREPARES to 'false'
        // For security reason
        $options = [PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'];

        /*\
         * The latter can be fixed by turning off emulation
         * and using the DSN charset attribute instead of SET NAMES.
         * The former is tricky, because you have no concept for safely
         * dealing with identifiers (they're just dumped straight into the query).
         * One possible approach would be to wrap all identifiers in backticks
         * while escaping all backticks within the identifiers (through doubling).
         * Whether this actually works in all cases is an open question, though.
        \*/

        try {
            $this->_pdo = new PDO($dsn, $username, $password, $options);
        } catch (PDOException $ex) {
            $this->_database->error('connect', $ex);
        }

        $this->_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
114244
public synchronized void connect_db() {

	//
	// Try to connect to the database
	//

	if (_daemon == true) {
	    boolean connected = false;
	    while (connected == false) {
		try {
		    db = ApiUtil.get_db_obj();
		    if (db == null) {
			Util.out4.println("Can't contact db server, will try later");
			try {
			    wait(_sleep_between_connect * 1000);
			} catch (final InterruptedException ex) {
			}
		    } else {
			connected = true;
		    }
		} catch (final Exception e) {
		    Util.out4.println("Can't contact db server, will try later");
		    try {
			wait(_sleep_between_connect * 1000);
		    } catch (final InterruptedException ex) {
		    }
		}
	    }
	} else {
	    try {
		db = ApiUtil.get_db_obj();
		if (db == null) {
		    System.err.println("Can't build connection to TANGO database server, exiting");
		    System.err.println("DB server host = " + db_host);
		    System.exit(-1);
		}

	    } catch (final Exception ex) {
		System.err.println("Can't build connection to TANGO database server, exiting");
		System.err.println("DB server host = " + db_host);
		System.exit(-1);
	    }
	}
	Util.out4.println("Connected to database");
    }
1013428
public function connect() {
    // Check that the SQLite3 extension is installed.
    if (!class_exists('SQLite3')) {
      throw new Exceptions\UnableToConnectException(
          'SQLite3 PHP extension is not available. It probably has not '.
          'been installed. Please install and configure it in order to use '.
          'SQLite3.'
      );
    }
    $filename = $this->config['SQLite3']['filename'];
    $busyTimeout = $this->config['SQLite3']['busy_timeout'];
    $openFlags = $this->config['SQLite3']['open_flags'];
    $encryptionKey = $this->config['SQLite3']['encryption_key'];
    // Connecting
    if (!$this->connected) {
      $this->link = new SQLite3($filename, $openFlags, $encryptionKey);
      if ($this->link) {
        $this->connected = true;
        $this->link->busyTimeout($busyTimeout);
        // Set database and connection options.
        $this->link->exec("PRAGMA encoding = \"UTF-8\";");
        $this->link->exec("PRAGMA foreign_keys = 1;");
        $this->link->exec("PRAGMA case_sensitive_like = 1;");
        // Create the preg_match and regexp functions.
        // TODO(hperrin): Add more of these functions to get rid of post-query checks.
        $this->link->createFunction('preg_match', 'preg_match', 2, SQLITE3_DETERMINISTIC);
        $this->link->createFunction('regexp', function ($pattern, $subject) {
          return !!$this->posixRegexMatch($pattern, $subject);
        }, 2, SQLITE3_DETERMINISTIC);
      } else {
        $this->connected = false;
        if ($filename === ':memory:') {
          throw new Exceptions\NotConfiguredException();
        } else {
          throw new Exceptions\UnableToConnectException('Could not connect.');
        }
      }
    }
    return $this->connected;
  }
1110033
public static function connect() :void {

		// configure the database and get the dns
		$dsn = self::configureAndGetDSN();

		// try to connect
		self::$_handle = new \PDO(
			$dsn, 
			self::$_config['username'] ?: null, 
			self::$_config['password'] ?: null
		);

		// check if connection the connexion failed
		if(!self::$_handle) {
			// throw an exception if it failed
			Throw new Exception('Database::connect() : Failed to connect', 500);
		}

		// if a before statement has to be executed
		if(self::$_config['before']) {
			// execute the before statement
			self::$_handle->query(self::$_config['before']);
		}
	}
371302
protected function connect()
    {
        if ($this->databaseHandle !== null) {
            return;
        }
        try {
            $splitdsn = explode(':', $this->dataSourceName, 2);
            $this->pdoDriver = $splitdsn[0];

            if ($this->pdoDriver === 'sqlite' && !file_exists($splitdsn[1])) {
                if (!file_exists(dirname($splitdsn[1]))) {
                    Files::createDirectoryRecursively(dirname($splitdsn[1]));
                }
                $this->databaseHandle = new \PDO($this->dataSourceName, $this->username, $this->password);
                $this->createCacheTables();
            } else {
                $this->databaseHandle = new \PDO($this->dataSourceName, $this->username, $this->password);
            }
            $this->databaseHandle->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

            if ($this->pdoDriver === 'mysql') {
                $this->databaseHandle->exec('SET SESSION sql_mode=\'ANSI\';');
            }
        } catch (\PDOException $exception) {
            throw new Exception('Could not connect to cache table with DSN "' . $this->dataSourceName . '". PDO error: ' . $exception->getMessage(), 1334736164);
        }
    }