Set the connection string for SQLAlchemy

    :param str connection: SQLAlchemy connection string
178163
def set_connection(connection=defaults.sqlalchemy_connection_string_default):
    
    cfp = defaults.config_file_path
    config = RawConfigParser()

    if not os.path.exists(cfp):
        with open(cfp, 'w') as config_file:
            config['database'] = {'sqlalchemy_connection_string': connection}
            config.write(config_file)
            log.info('create configuration file %s', cfp)
    else:
        config.read(cfp)
        config.set('database', 'sqlalchemy_connection_string', connection)
        with open(cfp, 'w') as configfile:
            config.write(configfile)
575010
def _get_connection(self):
        
        if not getattr(self, '_connection', None):
            logger.debug(
                'Creating new connection.\n   dsn: {}'
                .format(self._dsn))

            d = parse_url_to_dict(self._dsn)
            self._connection = psycopg2.connect(
                database=d['path'].strip('/'), user=d['username'], password=d['password'],
                port=d['port'], host=d['hostname'])
            # It takes some time to find the way how to get raw connection from sqlalchemy. So,
            # I leave the commented code.
            #
            # self._engine = create_engine(self._dsn)
            # self._connection = self._engine.raw_connection()
            #
        return self._connection
836755
def set_connection_string_by_user_input(self):
        """"""
        user_connection = input(
            bcolors.WARNING + "\nFor any reason connection to " + bcolors.ENDC +
            bcolors.FAIL + "{}".format(self.connection) + bcolors.ENDC +
            bcolors.WARNING + " is not possible.\n\n" + bcolors.ENDC +
            "For more information about SQLAlchemy connection strings go to:\n" +
            "http://docs.sqlalchemy.org/en/latest/core/engines.html\n\n"
            "Please insert a valid connection string:\n" +
            bcolors.UNDERLINE + "Examples:\n\n" + bcolors.ENDC +
            "MySQL (recommended):\n" +
            bcolors.OKGREEN + "\tmysql+pymysql://user:passwd@localhost/database?charset=utf8\n" + bcolors.ENDC +
            "PostgreSQL:\n" +
            bcolors.OKGREEN + "\tpostgresql://scott:tiger@localhost/mydatabase\n" + bcolors.ENDC +
            "MsSQL (pyodbc have to be installed):\n" +
            bcolors.OKGREEN + "\tmssql+pyodbc://user:passwd@database\n" + bcolors.ENDC +
            "SQLite (always works):\n" +
            " - Linux:\n" +
            bcolors.OKGREEN + "\tsqlite:////absolute/path/to/database.db\n" + bcolors.ENDC +
            " - Windows:\n" +
            bcolors.OKGREEN + "\tsqlite:///C:\\path\\to\\database.db\n" + bcolors.ENDC +
            "Oracle:\n" +
            bcolors.OKGREEN + "\toracle://user:passwd@127.0.0.1:1521/database\n\n" + bcolors.ENDC +
            "[RETURN] for standard connection {}:\n".format(defaults.sqlalchemy_connection_string_default)
        )
        if not (user_connection or user_connection.strip()):
            user_connection = defaults.sqlalchemy_connection_string_default
        set_connection(user_connection.strip())
264850
protected static function _connection(& $connection)
	{
		if (static::isString($connection))
			$connection = static::connection($connection);

		if (!$connection instanceof \PDO)
			throw new \InvalidArgumentException("invalid connection");
	}
680306
public function initConnection(Connection $connection)
    {
        /** @var $pdo PDO */
        $pdo = $connection->getWrappedConnection();
        $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
        $params = $connection->getParams();
        if (!isset($params['charset'])) {
            throw new RuntimeException("No connection charset specified");
        }
        $pdo->exec('SET NAMES ' . $pdo->quote($params['charset']));
    }
459607
def db_connect(engine, schema=None, clobber=False):
    

    if schema is None:
        base = declarative_base()
    else:
        try:
            engine.execute(sqlalchemy.schema.CreateSchema(schema))
        except sqlalchemy.exc.ProgrammingError as err:
            logging.warn(err)
        base = declarative_base(metadata=MetaData(schema=schema))

    define_schema(base)

    if clobber:
        logging.info('Clobbering database tables')
        base.metadata.drop_all(bind=engine)

    logging.info('Creating database tables')
    base.metadata.create_all(bind=engine)

    return base
84596
def SettingsAddConnection(self, connection_settings):
    '''
    '''

    if 'uuid' not in connection_settings['connection']:
        connection_settings['connection']['uuid'] = str(uuid.uuid4())

    NM = dbusmock.get_object(MANAGER_OBJ)
    settings_obj = dbusmock.get_object(SETTINGS_OBJ)
    main_connections = settings_obj.ListConnections()

    # Mimic how NM names connections
    count = 0
    while True:
        connection_obj_path = dbus.ObjectPath(SETTINGS_OBJ + '/' + str(count))
        if connection_obj_path not in main_connections:
            break
        count += 1
    connection_path = str(connection_obj_path)

    self.AddObject(connection_path,
                   CSETTINGS_IFACE,
                   {
                       'Unsaved': False
                   },
                   [
                       ('Delete', '', '', 'self.ConnectionDelete(self)'),
                       ('GetSettings', '', 'a{sa{sv}}', 'ret = self.ConnectionGetSettings(self)'),
                       ('GetSecrets', 's', 'a{sa{sv}}', 'ret = self.ConnectionGetSecrets(self, args[0])'),
                       ('Update', 'a{sa{sv}}', '', 'self.ConnectionUpdate(self, args[0])'),
                   ])
    self.object_manager_emit_added(connection_path)

    connection_obj = dbusmock.get_object(connection_path)
    connection_obj.settings = connection_settings
    connection_obj.connection_path = connection_path
    connection_obj.ConnectionDelete = ConnectionDelete
    connection_obj.ConnectionGetSettings = ConnectionGetSettings
    connection_obj.ConnectionGetSecrets = ConnectionGetSecrets
    connection_obj.ConnectionUpdate = ConnectionUpdate

    main_connections.append(connection_path)
    settings_obj.Set(SETTINGS_IFACE, 'Connections', main_connections)

    settings_obj.EmitSignal(SETTINGS_IFACE, 'NewConnection', 'o', [connection_path])

    auto_connect = False
    if 'autoconnect' in connection_settings['connection']:
        auto_connect = connection_settings['connection']['autoconnect']

    if auto_connect:
        dev = None
        devices = NM.GetDevices()

        # Grab the first device.
        if len(devices) > 0:
            dev = devices[0]

        if dev:
            activate_connection(NM, connection_path, dev, connection_path)

    return connection_path
274069
def set_network_connection(self, network):
        
        mode = network.mask if isinstance(network, self.ConnectionType) else network
        return self.ConnectionType(self._driver.execute(
            Command.SET_NETWORK_CONNECTION, {
                'name': 'network_connection',
                'parameters': {'type': mode}})['value'])
810609
def connect(self,
                engine: str = None,
                interface: str = None,
                host: str = None,
                port: int = None,
                database: str = None,
                driver: str = None,
                dsn: str = None,
                odbc_connection_string: str = None,
                user: str = None,
                password: str = None,
                autocommit: bool = True,
                charset: str = "utf8",
                use_unicode: bool = True) -> bool:
        

        # Catch all exceptions, so the error-catcher never shows a password.
        # Note also that higher-level things may catch exceptions, so use the
        # logger as well.
        try:
            return self._connect(
                engine=engine, interface=interface,
                host=host, port=port, database=database,
                driver=driver, dsn=dsn,
                odbc_connection_string=odbc_connection_string,
                user=user, password=password,
                autocommit=autocommit, charset=charset,
                use_unicode=use_unicode)
        except Exception as e:
            self.reraise_connection_exception(e)
184186
def _connect(dbapi_connection, connection_record):
    """"""

    # If back end is sqlite
    if type(dbapi_connection) is sqlite3.Connection:

        # Respect foreign key constraints by default
        cursor = dbapi_connection.cursor()
        cursor.execute("PRAGMA foreign_keys=ON")
        cursor.close()
797371
def connect(
    database: Union[str, Path], *, loop: asyncio.AbstractEventLoop = None, **kwargs: Any
) -> Connection:
    """"""
    if loop is None:
        loop = asyncio.get_event_loop()

    def connector() -> sqlite3.Connection:
        if isinstance(database, str):
            loc = database
        elif isinstance(database, bytes):
            loc = database.decode("utf-8")
        else:
            loc = str(database)

        return sqlite3.connect(loc, **kwargs)

    return Connection(connector, loop)
1095787
private function setConnection()
    {
        switch ($this->driver) {
            case 'mysql' :
                $this->connection = new Mysql($this->config);
                break;
            case 'postgresql' :
                $this->connection = new Postgresql($this->config);
                break;
            case 'sqlite' :
                $this->connection = new Sqlite($this->config);
                break;
            case 'oracle' :
                $this->connection = new Oracle($this->config);
                break;
            default :
                $debug_msg = "~/config/database.php文件配置错误！不支持的数据库驱动类型 - " . strval($this->driver);
                throw new \InvalidArgumentException($debug_msg);
        }
    }
247819
def add(self, connection):
        
        if id(connection) in self.connections:
            raise ValueError('Connection already exists in pool')

        if len(self.connections) == self.max_size:
            LOGGER.warning('Race condition found when adding new connection')
            try:
                connection.close()
            except (psycopg2.Error, psycopg2.Warning) as error:
                LOGGER.error('Error closing the conn that cant be used: %s',
                             error)
            raise PoolFullError(self)
        with self._lock:
            self.connections[id(connection)] = Connection(connection)
        LOGGER.debug('Pool %s added connection %s', self.id, id(connection))
1269866
def get_connection_string(connection=None):
    
    if not connection:
        config = configparser.ConfigParser()
        cfp = defaults.config_file_path
        if os.path.exists(cfp):
            log.info('fetch database configuration from %s', cfp)
            config.read(cfp)
            connection = config['database']['sqlalchemy_connection_string']
            log.info('load connection string from %s: %s', cfp, connection)
        else:
            with open(cfp, 'w') as config_file:
                connection = defaults.sqlalchemy_connection_string_default
                config['database'] = {'sqlalchemy_connection_string': connection}
                config.write(config_file)
                log.info('create configuration file %s', cfp)

    return connection
1240944
public void connect(Connection c) {

        schemaFilter = null;

        if (c == null) {
            return;
        }

        if (cConn != null) {
            try {
                cConn.close();
            } catch (SQLException e) {

                //  Added: (weconsultants@users)
                CommonSwing.errorMessage(e);
            }
        }

        cConn = c;

        // Added: (weconsultants@users) Need to barrow to get the table rowcounts
        rowConn = c;

        try {
            dMeta      = cConn.getMetaData();
            isOracle = (dMeta.getDatabaseProductName().indexOf("Oracle") >= 0);
            sStatement = cConn.createStatement();

            updateAutoCommitBox();

            // Workaround for EXTREME SLOWNESS getting this info from O.
            showIndexDetails = !isOracle;

            Driver driver = DriverManager.getDriver(dMeta.getURL());
            ConnectionSetting newSetting = new ConnectionSetting(
                dMeta.getDatabaseProductName(), driver.getClass().getName(),
                dMeta.getURL(),
                dMeta.getUserName().replaceAll("@localhost", ""), "");
            Hashtable settings =
                ConnectionDialogCommon.loadRecentConnectionSettings();

            ConnectionDialogCommon.addToRecentConnectionSettings(settings,
                    newSetting);
            ConnectionDialogSwing.setConnectionSetting(newSetting);
            refreshTree();
            clearResultPanel();

            if (fMain instanceof JApplet) {
                getAppletContext().showStatus(
                    "JDBC Connection established to a "
                    + dMeta.getDatabaseProductName() + " v. "
                    + dMeta.getDatabaseProductVersion() + " database as '"
                    + dMeta.getUserName() + "'.");
            }
        } catch (SQLException e) {

            //  Added: (weconsultants@users)
            CommonSwing.errorMessage(e);
        } catch (IOException e) {

            //  Added: (weconsultants@users)
            CommonSwing.errorMessage(e);
        } catch (Exception e) {
            CommonSwing.errorMessage(e);
        }
    }
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)
71965
def get_connection_cls(cls):
        
        if cls.__connection_cls is None:
            cls.__connection_cls, _ = cls.from_settings()
        return cls.__connection_cls