This method initializes a database connection

@param null
@return object Instance of this database connection
@throws DbException  If the database type provided is not defined for this system
4097
public function initialize()
	{
		//throw exception if no database type has been set
		if( ! $this->type )
		{
			//Throw exception
			throw new DbException("Invalid database type provided");
			
		}

		//check the type of  database provided returning instance
		//set the parameter to check in switch clause
		switch ($this->type ) 
		{
			case 'mysql':

				return new MySQL($this->options);

				break;
			
			default:

				throw new DbException("Valid database type provided");
				

				break;
		}

	}
394229
private void initAdapter()
    {
        Connection tmp = null;
        DatabaseMetaData meta = null;
        try
        {
            tmp = _ds.getConnection();
            meta = tmp.getMetaData();
            product = meta.getDatabaseProductName().toLowerCase();
        }
        catch (SQLException e)
        {
            throw new DatabaseException("Cannot connect to the database", e);
        }
        finally
        {
            try
            {
                if (tmp != null)
                {
                    tmp.close();
                }
            }
            catch (SQLException e)
            {
                // Nothing to do.
            }
        }

        DbAdapter newAdpt = null;
        for (String s : ADAPTERS)
        {
            try
            {
                Class<? extends DbAdapter> clazz = Db.class.getClassLoader().loadClass(s).asSubclass(DbAdapter.class);
                newAdpt = clazz.newInstance();
                if (newAdpt.compatibleWith(meta))
                {
                    adapter = newAdpt;
                    break;
                }
            }
            catch (Exception e)
            {
                throw new DatabaseException("Issue when loading database adapter named: " + s, e);
            }
        }

        if (adapter == null)
        {
            throw new DatabaseException("Unsupported database! There is no JQM database adapter compatible with product name " + product);
        }
        else
        {
            jqmlogger.info("Using database adapter {}", adapter.getClass().getCanonicalName());
        }
    }
550998
def init_db_conn(connection_name, connection_string, scopefunc=None):
    
    engine = create_engine(connection_string)
    session = scoped_session(sessionmaker(), scopefunc=scopefunc)
    session.configure(bind=engine)
    pool.connections[connection_name] = Connection(engine, session)
1063690
void createTable() {
        Connection con = null;
        java.sql.Statement s = null;

        //PK55900 We can pass in true to the getConnection method since this method,
        //createTable, is only called from the initDBSettings method.
        con = getConnection(true);
        if (con == null) {
            return;
        }

        try {

            try {
                s = con.createStatement();
                if (!getTableDefinition(con)) {
                    if (usingOracle) {
                        if (_smc.isUseOracleBlob()) { // cmd LI1963 start
                            s.executeUpdate("create table "
                                            + tableName
                                            + " (id varchar(128) not null, propid varchar(128) not null, appname varchar(128) not null, listenercnt smallint, lastaccess integer, creationtime integer, maxinactivetime integer, username varchar(256), small raw("
                                            + SMALLCOL_SIZE_ORACLE + "), medium BLOB, large raw(1))");
                        } else {
                            s.executeUpdate("create table "
                                            + tableName
                                            + " (id varchar(128) not null, propid varchar(128) not null, appname varchar(128) not null, listenercnt smallint, lastaccess integer, creationtime integer, maxinactivetime integer, username varchar(256), small raw("
                                            + SMALLCOL_SIZE_ORACLE + "), medium long raw, large raw(1))");
                        } // cmd LI1963 end
                    } else if (usingAS400DB2) {
                        try { //if using AS400, create collection first
                            s.executeUpdate("CREATE COLLECTION " + collectionName);
                        } catch (Exception e) {
                            com.ibm.ws.ffdc.FFDCFilter.processException(e, "com.ibm.ws.session.store.db.DatabaseHashMap.createTable", "470", con);
                        }
                        s.executeUpdate("create table "
                                        + tableName
                                        + " (id varchar(128) not null, propid varchar(128) not null, appname varchar(128) not null, listenercnt smallint, lastaccess bigint, creationtime bigint, maxinactivetime integer, username varchar(256), small varchar("
                                        + SMALLCOL_SIZE_DB2 + ") for bit data, medium long varchar for bit data, large BLOB(2M))");
                    } else if (usingSybase) {
                        s.executeUpdate("create table "
                                        + tableName
                                        + " (id varchar(128) not null, propid varchar(128) not null, appname varchar(128) not null, listenercnt smallint null, lastaccess numeric(21,0) null, creationtime numeric(21,0) null, maxinactivetime numeric(10,0) null, username varchar(255) null, small image null, medium image null, large image null)");
                    } else if (usingSQLServer) {
                        s.executeUpdate("create table "
                                        + tableName
                                        + " (id varchar(128) not null, propid varchar(128) not null, appname varchar(128) not null, listenercnt smallint null, lastaccess decimal(21,0) null, creationtime decimal(21,0) null, maxinactivetime integer null, username varchar(255) null, small image null, medium image null, large image null)");
                    } else if (usingInformix) {
                        s.executeUpdate("create table "
                                        + tableName
                                        + " (id varchar(128) not null, propid varchar(128) not null, appname varchar(128) not null, listenercnt smallint, lastaccess int8, creationtime int8, maxinactivetime integer, username varchar(255), small BYTE, medium BYTE, large BYTE)");
                    } else if (usingCloudScape) {
                        s.executeUpdate("create table "
                                        + tableName
                                        + " (id varchar(128) not null, propid varchar(128) not null, appname varchar(128) not null, listenercnt smallint, lastaccess bigint, creationtime bigint, maxinactivetime integer, username varchar(255), small LONG VARBINARY , medium char(1) , large char(1))");
                    } else if (dbHandler != null) {
                        dbHandler.createTable(s, tableName);
                    } else if (!usingDB2Connect && !usingDB2zOS) { // LIDB2775.25 zOS
                        String tableSpaceName = " ";
                        // a little overkill for this test
                        String configTableSpaceName = _smc.getTableSpaceName();
                        if (configTableSpaceName != null && !configTableSpaceName.equals("") && configTableSpaceName.length() != 0)
                            tableSpaceName = " in " + configTableSpaceName;
                        if (usingSolidDB)
                            s.executeUpdate("create table "
                                        + tableName
                                        + " (id varchar(128) not null, propid varchar(128) not null, appname varchar(128) not null, listenercnt smallint, lastaccess bigint, creationtime bigint, maxinactivetime integer, username varchar(256), small varchar("
                                        + smallColSize + "), medium long varchar, large BLOB(2M)) " + tableSpaceName);
                        else
                            s.executeUpdate("create table "
                                        + tableName
                                        + " (id varchar(128) not null, propid varchar(128) not null, appname varchar(128) not null, listenercnt smallint, lastaccess bigint, creationtime bigint, maxinactivetime integer, username varchar(256), small varchar("
                                        + smallColSize + ") for bit data, medium long varchar for bit data, large BLOB(2M)) " + tableSpaceName);
                    }
                }
                //            } catch (com.ibm.ejs.cm.portability.TableAlreadyExistsException eee) {
                //                // Do nothing since all is well!!
                //                com.ibm.ws.ffdc.FFDCFilter.processException(eee, "com.ibm.ws.session.store.db.DatabaseHashMap.createTable", "495", this);
            } catch (SQLException err) {
                com.ibm.ws.ffdc.FFDCFilter.processException(err, "com.ibm.ws.session.store.db.DatabaseHashMap.createTable", "497", this);
                if (!usingCloudScape) {
                    LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[CREATE_TABLE], "CommonMessage.exception", err);
                } else {
                    if (err.getErrorCode() != 30000)
                        LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[CREATE_TABLE], "CommonMessage.exception", err);
                }
            }

            if (!_smc.isSessionTableSkipIndexCreation()) { // PM37139

                //Creating index in a seperate step as we have seen customers missing this
                //step when they create the table manually
                try {
                    if (s == null)
                        s = con.createStatement();
                    if (usingSybase) {
                        s.executeUpdate("create unique index sess_index on " + tableName + " (id, propid, appname)");
                        s.executeUpdate("alter table sessions lock datarows");
                    } else if (usingSolidDB) {
                        s.executeUpdate("create unique index sess_index on " + tableName + " (id, propid, appname)");
                    } else if (usingAS400DB2) {
                        mediumColSize = mediumColSize - 2; //d154211
                        //PK56991: If multiple cluster members startup at the same time the
                        // combination of these DDLs can lock up for a substantial duration.
                        // We now execute these only if they do not exist.
                        if (!doesIndexExists(con, "sess_index")) {
                            s.executeUpdate("create unique index " + collectionName + ".sess_index on " + tableName + " (id,propid,appname)"); //tableName is already in the form of "collectionName.tableName"
                            //PK56991 comment out marking table as volatile. The DB2 chief architect on iSeries
                            //team informed that VOLATILE clause is only compatible and improve performance on LUW
                            //s.executeUpdate("alter table " + tableName + " volatile");
                        } else if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
                            LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[CREATE_TABLE], "Skip index creation");
                        }
                    } else if (dbHandler != null) {
                        dbHandler.createIndex(con, s, tableName);
                    } else if (!usingDB2Connect && !usingDB2zOS) { // LIDB2775.25
                        //PK56991: Refer to detailed comment above
                        if (!doesIndexExists(con, "sess_index")) {
                            s.executeUpdate("create unique index sess_index on " + tableName + " (id, propid, appname)");//PK86373: changed sesscmd_index to sess_index
                        } else if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
                            LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[CREATE_TABLE], "Skip index creation");
                        }
                        //PK56991: We are marking the the session table as volatile if it is not
                        //done yet.
                        if (usingDB2 && !isTableMarkedVolatile(con)) {
                            s.executeUpdate("alter table " + tableName + " volatile");
                        } else if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
                            LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[CREATE_TABLE], "Skip marking table volatile");
                        }

                    }
                } catch (SQLException err) {
                    //Don't do any thing if it is only index already exists
                    //err.printStackTrace();
                    com.ibm.ws.ffdc.FFDCFilter.processException(err, "com.ibm.ws.session.store.db.DatabaseHashMap.createTable", "526", con);
                }
            } // END PM37139
        } finally {
            if (s != null)
                closeStatement(s);
                closeConnection(con); //findbugs for 106329
        }
    }
640187
private void init_jdbcTypes() throws SQLException
    {
        ReportQuery q = (ReportQuery) getQueryObject().getQuery();
        m_jdbcTypes = new int[m_attributeCount];
        
        // try to get jdbcTypes from Query
        if (q.getJdbcTypes() != null)
        {
            m_jdbcTypes = q.getJdbcTypes();
        }
        else
        {
            ResultSetMetaData rsMetaData = getRsAndStmt().m_rs.getMetaData();
            for (int i = 0; i < m_attributeCount; i++)
            {
                m_jdbcTypes[i] = rsMetaData.getColumnType(i + 1);
            }
            
        }
    }
1216881
private Connection createConnection() {

    if (mConnInfo != null) {
      DBConnCreator dbConnCreator = new DBConnCreator(mConnInfo);
      Connection conn = dbConnCreator.createDBConnection();
      return conn;
    } else if (mDbcpPropertyFile != null) {
      Properties properties = new Properties();
      InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(mDbcpPropertyFile);
      try {
        properties.load(is);
        DataSource ds;
        ds = BasicDataSourceFactory.createDataSource(properties);
        Connection conn = ds.getConnection();
        return conn;
      } catch (IOException e) {
        e.printStackTrace();
      } catch (Exception e) {
        e.printStackTrace();
      }

    }
    return null;

  }
1087722
private function connect()
    {
        // Connecting with PDO.
        try {
            switch ($this->dbType) {
                case 'sqlite':
                    $this->dbHandler = @new PDO("sqlite:".$this->dbName, null, null, $this->pdoSettings);
                    break;
                case 'mysql':
                case 'pgsql':
                case 'dblib':
                    $this->dbHandler = @new PDO(
                        $this->dsn,
                        $this->user,
                        $this->pass,
                        $this->pdoSettings
                    );
                    // Execute init commands once connected
                    foreach ($this->dumpSettings['init_commands'] as $stmt) {
                        $this->dbHandler->exec($stmt);
                    }
                    // Store server version
                    $this->version = $this->dbHandler->getAttribute(PDO::ATTR_SERVER_VERSION);
                    break;
                default:
                    throw new Exception("Unsupported database type (".$this->dbType.")");
            }
        } catch (PDOException $e) {
            throw new Exception(
                "Connection to ".$this->dbType." failed with message: ".
                $e->getMessage()
            );
        }

        if (is_null($this->dbHandler)) {
            throw new Exception("Connection to ".$this->dbType."failed");
        }

        $this->dbHandler->setAttribute(PDO::ATTR_ORACLE_NULLS, PDO::NULL_NATURAL);
        $this->typeAdapter = TypeAdapterFactory::create($this->dbType, $this->dbHandler, $this->dumpSettings);
    }
625290
function databaseInitialize() {
  // on the first load of (non-existent database), we will have no collections so we can 
  //   detect the absence of our collections and add (and configure) them now.
  var entries = db.getCollection("entries");
  if (entries === null) {
    entries = db.addCollection("entries");
  }

  // kick off any program logic or start listening to external events
  runProgramLogic();
}
850822
public boolean setupDirectDataSourceConnection() throws DBException
    {
        if (m_JDBCConnection != null)
            return true;
        try {
            if (m_datasourceFactory == null)
            {
                String strClassName = this.getProperty(SQLParams.DATASOURCE_FACTORY);
            	strClassName = ClassServiceUtility.getFullClassName(strClassName);
                try {
                	m_datasourceFactory = (DatasourceFactory)ClassServiceUtility.getClassService().makeObjectFromClassName(strClassName);
             	    //xClass<?> c = Class.forName(strClassName);
             	    //xm_datasourceFactory = (DatasourceFactory)c.newInstance();
                } catch (Exception e) {
            		Utility.getLogger().warning("Error on create class: " + strClassName);
            		e.printStackTrace();
                }
            }
            if (m_datasourceFactory == null)
                return false;   // No factory
            ConnectionPoolDataSource poolDataSource = m_datasourceFactory.getPooledDataSource(this);
            if (poolDataSource != null)
            	if (poolDataSource.getPooledConnection() != null)
            		m_JDBCConnection = poolDataSource.getPooledConnection().getConnection();
            if (m_JDBCConnection == null)
            {   // Otherwise, just try plain datasource connection
                DataSource dataSource = m_datasourceFactory.getFakePooledDataSource(this);
                if (dataSource != null)
                    m_JDBCConnection = dataSource.getConnection();
            }
            if (m_JDBCConnection == null)
            {   // Otherwise, just try plain datasource connection
                DataSource dataSource = m_datasourceFactory.getDataSource(this);
                if (dataSource != null)
                    m_JDBCConnection = dataSource.getConnection();
                else
                    return false;   // Failure
            }
        } catch (SQLException e) {
            return false;   // Failure
        }
        return true;    // Success!
    }
1155158
protected function connect() {
		$connection = new co\Redis();
		$r = $connection->connect($this->config['host'], $this->config['port']);
		if ($r === false) {
			throw new DBException('Can not connect to database server, ' . $connection->errMsg, $connection->errCode);
		}
		if (!empty($this->config['password'])) {
			$r = $connection->auth($this->config['password']);
			if ($r === false) {
				throw new ConnectionException('Authenticate failed, ' . $connection->errMsg, $connection->errCode);
			}
		}
		if (isset($this->config['index'])) {
			$r = $connection->select(intval($this->config['index']));
			if ($r === false) {
				throw new ConnectionException('Select database failed, ' . $connection->errMsg, $connection->errCode);
			}
		}
		foreach ($this->options as $k => $v) {
			$connection->setOption($k, $v);
		}
		return $connection;
	}
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);
        }
    }
498346
public function connect() {
		try {
			$this->_connect ();
			return true;
		} catch ( \PDOException $e ) {
			throw new DBException ( $e->getMessage (), $e->getCode (), $e->getPrevious () );
		}
	}
280490
private void initFromDatabase() throws SQLException, BlockStoreException {
        PreparedStatement ps = conn.get().prepareStatement(getSelectSettingsSQL());
        ResultSet rs;
        ps.setString(1, CHAIN_HEAD_SETTING);
        rs = ps.executeQuery();
        if (!rs.next()) {
            throw new BlockStoreException("corrupt database block store - no chain head pointer");
        }
        Sha256Hash hash = Sha256Hash.wrap(rs.getBytes(1));
        rs.close();
        this.chainHeadBlock = get(hash);
        this.chainHeadHash = hash;
        if (this.chainHeadBlock == null) {
            throw new BlockStoreException("corrupt database block store - head block not found");
        }
        ps.setString(1, VERIFIED_CHAIN_HEAD_SETTING);
        rs = ps.executeQuery();
        if (!rs.next()) {
            throw new BlockStoreException("corrupt database block store - no verified chain head pointer");
        }
        hash = Sha256Hash.wrap(rs.getBytes(1));
        rs.close();
        ps.close();
        this.verifiedChainHeadBlock = get(hash);
        this.verifiedChainHeadHash = hash;
        if (this.verifiedChainHeadBlock == null) {
            throw new BlockStoreException("corrupt database block store - verified head block not found");
        }
    }
1325228
void init() {
        if (dataSource == null) {
            if (connectionType.equals(ConnectionType.POOLED)) {
                HikariConfig config = new HikariConfig();
                config.setMaximumPoolSize(maximumPoolSize);
                config.setDataSourceClassName(dataSourceClass);
                config.addDataSourceProperty("url", url);
                config.addDataSourceProperty("user", user);
                config.addDataSourceProperty("password", password);
                config.setPoolName(CONNECTION_POOL_NAME);
                config.setAutoCommit(autoCommit);
                config.setMaximumPoolSize(maximumPoolSize);
              //  config.setConnectionTestQuery("SELECT 1");
                
                if (connectionTimeout != null) {
                    config.setConnectionTimeout(connectionTimeout);
                }
                if (idleTimeout != null) {
                    config.setIdleTimeout(idleTimeout);
                }
                if (maxLifetime != null) {
                    config.setMaxLifetime(maxLifetime);
                }
                if (minimumIdle != null) {
                    config.setMinimumIdle(minimumIdle);
                }

                ds = new HikariDataSource(config);
                dataSource = ds;

            } else if (connectionType.equals(ConnectionType.JNDI)) {
                if (null == jndiDataSource) {
                    throw new InitializationException("Could not obtain the db connection: jndi data source is null");
                }
                String DATASOURCE_CONTEXT = jndiDataSource;
                try {
                    Context initialContext = new InitialContext();
                    dataSource = (DataSource) initialContext.lookup(DATASOURCE_CONTEXT);
                    if (dataSource == null) {
                        Log.error("Failed to lookup datasource.");
                        throw new InitializationException(
                                "Could not obtain the db connection: Failed to lookup datasource: " + jndiDataSource);
                    }
                } catch (NamingException ex) {
                    throw new InitializationException("Could not obtain the db connection: jndi lookup failed", ex);
                }
            }
        }
    }
678452
protected void setUp() throws SQLException {
		Connection c = null;
		try {
			c = DriverManager.getConnection("jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1");
			Statement stmt = c.createStatement();
			stmt.execute("create table foo (id number(6), dsc varchar2(256))");
			stmt.close();
		} finally {
			if (c != null) {
				c.close();
			}
		}
	}
155639
public int create() throws SQLException {
		checkForDao();
		@SuppressWarnings("unchecked")
		T t = (T) this;
		return dao.create(t);
	}
1008027
public Connection getConnection() throws SQLException {
    try {
      if (pool == null) {
        initialize();
      }
      return pool.getConnection();
    } catch (SQLException e) {
      throw ExceptionMapper.getException(e, null, null, false);
    }
  }