Acquires a database connection based on parameters.
Parses the insert pattern to create a chain of converters which will be
used in forming query parameters from logging events.
506450
public function activateOptions() {
		try {
			$this->establishConnection();
		} catch (\PDOException $e) {
			$this->warn("Failed connecting to database. Closing appender. Error: " . $e->getMessage());
			$this->close();
			return;
		}

		// Parse the insert patterns; pattern parts are comma delimited
		$pieces = explode(',', $this->insertPattern);
		$converterMap = \n2n\log4php\layout\LayoutPattern::getDefaultConverterMap();
		foreach($pieces as $pattern) {
			$parser = new \n2n\log4php\pattern\PatternParser($pattern, $converterMap);
			$this->converters[] = $parser->parse(); 
		}
		
		$this->closed = false;
	}
1312468
protected function establishConnection() {
		// Acquire database connection
		$this->db = new \PDO($this->dsn, $this->user, $this->password);
		$this->db->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
		
		// Prepare the insert statement
		$insertSQL = str_replace('__TABLE__', $this->table, $this->insertSQL);
		$this->preparedInsert = $this->db->prepare($insertSQL);
	}
1357387
public void logInsertQueriesForCurrentThread() {
		List<String> queries = getInsertQueriesForCurrentThread()
			.stream()
			.map(CircularQueueCaptureQueriesListener::formatQueryAsSql)
			.collect(Collectors.toList());
		ourLog.info("Insert Queries:\n{}", String.join("\n", queries));
	}
1164372
def connect_to_database(db_settings, force = false)
      # only setup database connection once
      if force
        ActiveRecord::Base.establish_connection(db_settings)
      else
        begin
          ActiveRecord::Base.connection
        rescue => e
          require 'pp'
          pp db_settings
          puts "failed to connect: #{e}"
          ActiveRecord::Base.establish_connection(db_settings)
        end
      end
    end
310624
def _get_query(self, callback, schema, query=None, *args, **kwargs):
        """"""
        if not query: query = Query()

        ret = None
        with self.connection(**kwargs) as connection:
            kwargs['connection'] = connection
            try:
                if connection.in_transaction():
                    # we wrap SELECT queries in a transaction if we are in a transaction because
                    # it could cause data loss if it failed by causing the db to discard
                    # anything in the current transaction if the query isn't wrapped,
                    # go ahead, ask me how I know this
                    with self.transaction(**kwargs):
                        ret = callback(schema, query, *args, **kwargs)

                else:
                    ret = callback(schema, query, *args, **kwargs)

            except Exception as e:
                exc_info = sys.exc_info()
                if self.handle_error(schema, e, **kwargs):
                    ret = callback(schema, query, *args, **kwargs)
                else:
                    self.raise_error(e, exc_info)

        return ret
1066604
public int create(DatabaseConnection databaseConnection, T data, ObjectCache objectCache) throws SQLException {
		if (mappedInsert == null) {
			mappedInsert = MappedCreate.build(dao, tableInfo);
		}
		int result = mappedInsert.insert(databaseType, databaseConnection, data, objectCache);
		if (dao != null && !localIsInBatchMode.get()) {
			dao.notifyChanges();
		}
		return result;
	}
1103475
def __connect(self):
        
        self.__methods     = _get_methods_by_uri(self.sqluri)
        uri_connect_method = self.__methods[METHOD_CONNECT]

        self.__dbapi2_conn = uri_connect_method(self.sqluri)
898747
def _insert(self, query, vars):
        
        cursor = self.get_db().cursor()
        self._log(cursor, query, vars)
        cursor.execute(query, vars)
        self.get_db().commit()
        return cursor.fetchone()
151762
function parseDB(callback) {
    pgStructure(getConfig('database.host'), getConfig('database.database'), getConfig('database.user'),
        getConfig('database.password'), { port: getConfig('database.port'), schema: getConfig('database.schema') },
        callback);
}
630655
def _construct_inserts(self, record, new_columns, rename_columns, retype_columns, resize_columns):

        '''  '''

        insert_kwargs = {}

        for key, value in new_columns.items():

        # retrieve value for key (or from old key name)
            if key in rename_columns.keys():
                record_value = getattr(record, rename_columns[key], None)
            else:
                record_value = getattr(record, key, None)

        # attempt to convert datatype
            if record_value:
                if key in retype_columns.keys():
                    try:
                        old_list = False
                        if isinstance(record_value, bytes):
                            record_value = pickle.loads(record_value)
                            old_list = True
                        if retype_columns[key] == 'boolean':
                            record_value = bool(record_value)
                        elif retype_columns[key] == 'string':
                            if old_list:
                                record_value = ','.join(record_value)
                            else:
                                record_value = str(record_value)
                        elif retype_columns[key] == 'integer':
                            if old_list:
                                record_value = int(record_value[0])
                            else:
                                record_value = int(record_value)
                        elif retype_columns[key] == 'float':
                            if old_list:
                                record_value = int(record_value[0])
                            else:
                                record_value = float(record_value)
                        elif retype_columns[key] == 'list':
                            if isinstance(record_value, str):
                                record_value = pickle.dumps(record_value.split(','))
                            else:
                                record_value = pickle.dumps([record_value])
                    except:
                        record_value = None
        
        # attempt to resize string data 
                if key in resize_columns.keys():
                    max_length = resize_columns[key]
                    try:
                        if len(record_value) > max_length:
                            record_value = record_value[0:max_length]
                    except:
                        record_value = None

                insert_kwargs[key] = record_value

        return insert_kwargs
1025282
function (database, callback) {
        var s = this,
            querier = s._querier;
        querier.connect();
        async.waterfall([
            function (callback) {
                querier.showTables(database, function (err, tables) {
                    callback(err, tables);
                });
            },
            function (tables, callback) {
                var tableNames = s._parseTableNames(tables);
                async.map(tableNames, function (table, callback) {
                    querier.selectKeyColumnUsage(database, table, function (err, data) {
                        callback(err, {
                            name: table,
                            keyColumnUsage: s._parseTableKeyColumnUsageData(data)
                        });
                    });
                }, callback);
            },
            function (data, callback) {
                var database = {};
                data.forEach(function (data) {
                    database[data.name] = data.keyColumnUsage;
                });
                callback(null, database);
            }
        ], function (err, result) {
            querier.disconnect();
            callback(err, result);
        });
        return s;
    }
1128551
public static function initializeDatabaseConnections()
    {
        // for backward compatibility, don't use MAX_DB_CONNECTION_INDEX directly,
        // but check if MAX_DB_CONNECTION_INDEX is defined
        $intMaxIndex = defined('MAX_DB_CONNECTION_INDEX') ? constant('MAX_DB_CONNECTION_INDEX') : 9;

        if (defined('DB_CONNECTION_0')) {
            // This causes a conflict with how DbBackedSessionHandler works.
            throw new \Exception('Do not define DB_CONNECTION_0. Start at DB_CONNECTION_1');
        }

        for ($intIndex = 1; $intIndex <= $intMaxIndex; $intIndex++) {
            $strConstantName = sprintf('DB_CONNECTION_%s', $intIndex);

            if (defined($strConstantName)) {
                // Expected Keys to be Set
                $strExpectedKeys = array(
                    'adapter',
                    'server',
                    'port',
                    'database',
                    'username',
                    'password',
                    'profiling',
                    'dateformat'
                );

                // Lookup the Serialized Array from the DB_CONFIG constants and unserialize it
                $strSerialArray = constant($strConstantName);
                $objConfigArray = unserialize($strSerialArray);

                // Set All Expected Keys
                foreach ($strExpectedKeys as $strExpectedKey) {
                    if (!array_key_exists($strExpectedKey, $objConfigArray)) {
                        $objConfigArray[$strExpectedKey] = null;
                    }
                }

                if (!$objConfigArray['adapter']) {
                    throw new \Exception('No Adapter Defined for ' . $strConstantName . ': ' . var_export($objConfigArray,
                            true));
                }

                if (!$objConfigArray['server']) {
                    throw new \Exception('No Server Defined for ' . $strConstantName . ': ' . constant($strConstantName));
                }

                $strDatabaseType = 'QCubed\\Database\\' . $objConfigArray['adapter'] . '\\Database';

                //if (!class_exists($strDatabaseType)) {
                //	throw new \Exception('Database adapter was not found: ' . $objConfigArray['adapter']);
                //}

                self::$Database[$intIndex] = new $strDatabaseType($intIndex, $objConfigArray);
            }
        }
    }
374487
protected function getConnectionParameters()
    {
        /** Collect the parameters, that are necessary to initialize the database connection: */

        /**
         * @var string $databaseDriver At the moment the database adapter uses always 'pdo_mysql'.
         */
        $databaseDriver = $this->getConfigParam('dbType');
        /**
         * @var string $databaseHost The database host to connect to.
         * Be aware, that the connection between the MySQL client and the server is unencrypted.
         */
        $databaseHost = $this->getConfigParam('dbHost');
        /**
         * @var integer $databasePort TCP port to connect to.
         */
        $databasePort = (int) $this->getConfigParam('dbPort');
        if (!$databasePort) {
            $databasePort = 3306;
        }
        /**
         * @var string $databaseName The name of the database or scheme to connect to.
         */
        $databaseName = $this->getConfigParam('dbName');
        /**
         * @var string $databaseUser The user id of the database user.
         */
        $databaseUser = $this->getConfigParam('dbUser');
        /**
         * @var string $databasePassword The password of the database user.
         */
        $databasePassword = $this->getConfigParam('dbPwd');

        $connectionParameters = [
            'default' => [
                'databaseDriver'    => $databaseDriver,
                'databaseHost'      => $databaseHost,
                'databasePort'      => $databasePort,
                'databaseName'      => $databaseName,
                'databaseUser'      => $databaseUser,
                'databasePassword'  => $databasePassword,
            ]
        ];

        /**
         * The charset has to be set during the connection to the database.
         */
        $charset = (string) $this->getConfigParam('dbCharset');
        //backwards compatibility with old config files.
        if (null == $charset) {
            $charset = 'utf8';
        }
        
        $connectionParameters['default'] = array_merge($connectionParameters['default'], ['connectionCharset' => $charset]);

        return $connectionParameters;
    }
765870
function Connect()
	{
		$this->handler->Log(DBH_LOG_INFO, "Opening Connection...");
		if ($this->dbopen)
		{
			$this->handler->Log(DBH_LOG_WARNING, "Connection Already Open");
		}
		else
		{
			$this->adapter = new DataAdapter($this->csetting);
			
			try {
				$this->adapter->Open();
			}
			catch (Exception $ex) {
				$this->handler->Crash(DatabaseException::$CONNECTION_ERROR,$ex->getMessage());
			}

			$this->handler->Log(DBH_LOG_INFO, "Connection Open");
			$this->dbopen = true;
		}
	}
18806
public static Object convertBlob(Connection conn, InputStream input) throws SQLException {
        return convertBlob(conn, toByteArray(input));
    }
580479
@Override
	public synchronized RecordParam insert(String site, String type, String name, int used, String flags,
			String values) throws DatabaseException {
    	SqlPreparedStatementWrapper psInsert = null;
        try {
        	psInsert = DbSQL.getSingleton().getPreparedStatement("param.ps.insert");
			psInsert.getPs().setString(1, site);
			psInsert.getPs().setString(2, type);
			psInsert.getPs().setString(3, name);
			psInsert.getPs().setInt(4, used);
			psInsert.getPs().setString(5, flags);
			psInsert.getPs().setString(6, values);
			psInsert.getPs().executeUpdate();
			
			long id;
			try (ResultSet rs = psInsert.getLastInsertedId()) {
				rs.next();
				id = rs.getLong(1);
			}
			return read(id);
		} catch (SQLException e) {
			throw new DatabaseException(e);
		} finally {
			DbSQL.getSingleton().releasePreparedStatement(psInsert);
		}
    }
905675
ConnectionWrapper obtainConnection() {
		synchronized (allConnections) {
			//fails if connection pool not started
			if (!availableConnections.isEmpty()) {
				//retrieve and remove first connection from list
				//  since released connections are added to the back, connections will rotate
				ConnectionWrapper connWrap = (ConnectionWrapper) availableConnections.remove(0);
				usedConnections.add(connWrap);
				if (usedConnections.size() > maxNrOfConcurrentConnectionsCounted) {
					maxNrOfConcurrentConnectionsCounted = usedConnections.size();
				}
				return connWrap;
			} else {
				//create one if max not reached
				//this also restores lost connections
				if ((allConnections.size() < initialNrofConnections) || (allConnections.size() < maxNrofConnections)) {
					try {
						ConnectionWrapper connWrap = createConnectionWrapper(dbUrl, dbUsername, dbUserpassword);

						allConnections.add(connWrap);
						usedConnections.add(connWrap);

						System.out.println(new LogEntry("Creating new Connection, now " + allConnections.size() + " in use"));

						return connWrap;
					} catch (SQLException sqle) {
						//happens if db unreachable
						//connection will be lost for the time being
						nrofErrors++;
						System.out.println(new LogEntry("Cannot create new connection to " + dbUrl + " unreachable or useless connection settings", sqle));
						throw new ResourceException("Cannot create new connection to " + dbUrl + " unreachable or useless connection settings", sqle);
					}
				} else {
					System.out.println(new LogEntry("maximum nr of connections (" + maxNrofConnections + ") reached while Application demands another"));
				}
				return null;
			}
		}
	}