query
stringlengths
9
60
language
stringclasses
1 value
code
stringlengths
105
25.7k
url
stringlengths
91
217
connect to sql
python
def connect(self): """ Create a SQL Server connection and return a connection object """ connection = _mssql.connect(user=self.user, password=self.password, server=self.host, port=self.port, database=self.database) return connection
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/mssqldb.py#L119-L128
connect to sql
python
def _connect(self): """Connect to the MySQL database. """ try: db = pymysql.connect(user=self.user, passwd=self.passwd, host=self.host, port=self.port, db=self.shdb, use_unicode=True) return db, db.cursor() except Exception: logger.error("Database connection error") raise
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/database.py#L44-L55
connect to sql
python
def connect(self, db_uri, debug=False): """Configure connection to a SQL database. Args: db_uri (str): path/URI to the database to connect to debug (Optional[bool]): whether to output logging information """ kwargs = {'echo': debug, 'convert_unicode': True} # connect to the SQL database if 'mysql' in db_uri: kwargs['pool_recycle'] = 3600 elif '://' not in db_uri: logger.debug("detected sqlite path URI: {}".format(db_uri)) db_path = os.path.abspath(os.path.expanduser(db_uri)) db_uri = "sqlite:///{}".format(db_path) self.engine = create_engine(db_uri, **kwargs) logger.debug('connection established successfully') # make sure the same engine is propagated to the BASE classes BASE.metadata.bind = self.engine # start a session self.session = scoped_session(sessionmaker(bind=self.engine)) # shortcut to query method self.query = self.session.query return self
https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/plugins/sql/store.py#L62-L86
connect to sql
python
async def _connect(self) -> "Connection": """Connect to the actual sqlite database.""" if self._connection is None: self._connection = await self._execute(self._connector) return self
https://github.com/jreese/aiosqlite/blob/3f548b568b8db9a57022b6e2c9627f5cdefb983f/aiosqlite/core.py#L169-L173
connect to sql
python
def __connect(self): """ Connect to the database. """ self.__methods = _get_methods_by_uri(self.sqluri) uri_connect_method = self.__methods[METHOD_CONNECT] self.__dbapi2_conn = uri_connect_method(self.sqluri)
https://github.com/decryptus/sonicprobe/blob/72f73f3a40d2982d79ad68686e36aa31d94b76f8/sonicprobe/libs/anysql.py#L360-L367
connect to sql
python
def sql( state, host, sql, database=None, # Details for speaking to MySQL via `mysql` CLI mysql_user=None, mysql_password=None, mysql_host=None, mysql_port=None, ): ''' Execute arbitrary SQL against MySQL. + sql: SQL command(s) to execute + database: optional database to open the connection with + mysql_*: global module arguments, see above ''' yield make_execute_mysql_command( sql, database=database, user=mysql_user, password=mysql_password, host=mysql_host, port=mysql_port, )
https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/modules/mysql.py#L24-L46
connect to sql
python
def _connect(self, config): """Establish a connection with a MySQL database.""" if 'connection_timeout' not in self._config: self._config['connection_timeout'] = 480 try: self._cnx = connect(**config) self._cursor = self._cnx.cursor() self._printer('\tMySQL DB connection established with db', config['database']) except Error as err: if err.errno == errorcode.ER_ACCESS_DENIED_ERROR: print("Something is wrong with your user name or password") elif err.errno == errorcode.ER_BAD_DB_ERROR: print("Database does not exist") raise err
https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/connector.py#L74-L87
connect to sql
python
def connect(self, url: str): """Connect to the database and set it as main database :param url: path to the database, uses the Sqlalchemy format :type url: str :example: ``ds.connect("sqlite:///mydb.slqite")`` """ try: self.db = dataset.connect(url, row_type=stuf) except Exception as e: self.err(e, "Can not connect to database") return if self.db is None: self.err("Database " + url + " not found") return self.ok("Db", self.db.url, "connected")
https://github.com/synw/dataswim/blob/4a4a53f80daa7cd8e8409d76a19ce07296269da2/dataswim/db/__init__.py#L23-L39
connect to sql
python
def as_sql(self, qn, connection): """ Create the proper SQL fragment. This inserts something like "(T0.flags & value) != 0". This will be called by Where.as_sql() """ engine = connection.settings_dict['ENGINE'].rsplit('.', -1)[-1] if engine.startswith('postgres'): XOR_OPERATOR = '#' elif engine.startswith('sqlite'): raise NotImplementedError else: XOR_OPERATOR = '^' if self.bit: return ("%s.%s | %d" % (qn(self.table_alias), qn(self.column), self.bit.mask), []) return ("%s.%s %s %d" % (qn(self.table_alias), qn(self.column), XOR_OPERATOR, self.bit.mask), [])
https://github.com/disqus/django-bitfield/blob/a6502aa1cb810620f801e282dc5a7330064fbbf5/bitfield/query.py#L53-L72
connect to sql
python
def _connect(self, database=None): """ Connect to given database """ conn_args = { 'host': self.config['host'], 'user': self.config['user'], 'password': self.config['password'], 'port': self.config['port'], 'sslmode': self.config['sslmode'], } if database: conn_args['database'] = database else: conn_args['database'] = 'postgres' # libpq will use ~/.pgpass only if no password supplied if self.config['password_provider'] == 'pgpass': del conn_args['password'] try: conn = psycopg2.connect(**conn_args) except Exception as e: self.log.error(e) raise e # Avoid using transactions, set isolation level to autocommit conn.set_isolation_level(0) return conn
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/postgres/postgres.py#L150-L179
connect to sql
python
def connect(self): """ Connects to the database server. """ with warnings.catch_warnings(): warnings.filterwarnings('ignore', '.*deprecated.*') self._conn = client.connect( init_command=self.init_fun, sql_mode="NO_ZERO_DATE,NO_ZERO_IN_DATE,ERROR_FOR_DIVISION_BY_ZERO," "STRICT_ALL_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION", charset=config['connection.charset'], **self.conn_info) self._conn.autocommit(True)
https://github.com/datajoint/datajoint-python/blob/4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c/datajoint/connection.py#L88-L100
connect to sql
python
def connect(cls, dbname): """Create a new connection to the SQLite3 database. :param dbname: The database name :type dbname: str """ test_times_schema = """ CREATE TABLE IF NOT EXISTS test_times ( file text, module text, class text, func text, elapsed float ) """ setup_times_schema = """ CREATE TABLE IF NOT EXISTS setup_times ( file text, module text, class text, func text, elapsed float ) """ schemas = [test_times_schema, setup_times_schema] db_file = '{}.db'.format(dbname) cls.connection = sqlite3.connect(db_file) for s in schemas: cls.connection.execute(s)
https://github.com/etscrivner/nose-perfdump/blob/a203a68495d30346fab43fb903cb60cd29b17d49/perfdump/connection.py#L38-L72
connect to sql
python
def _connect(self): """ Connect to the MySQL server """ self._close() self.conn = MySQLdb.Connect(host=self.hostname, port=self.port, user=self.username, passwd=self.password, db=self.database)
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/mysql.py#L92-L101
connect to sql
python
def connect( database: Union[str, Path], *, loop: asyncio.AbstractEventLoop = None, **kwargs: Any ) -> Connection: """Create and return a connection proxy to the sqlite database.""" 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)
https://github.com/jreese/aiosqlite/blob/3f548b568b8db9a57022b6e2c9627f5cdefb983f/aiosqlite/core.py#L287-L304
connect to sql
python
def connect(self, host='127.0.0.1', port=3306, user='root', password='', database=None): """ Connect to the database specified """ if database is None: raise exceptions.RequiresDatabase() self._db_args = { 'host': host, 'port': port, 'user': user, 'password': password, 'database': database } with self._db_conn() as conn: conn.query('SELECT 1') return self
https://github.com/memsql/memsql-python/blob/aac223a1b937d5b348b42af3c601a6c685ca633a/memsql/common/sql_utility.py#L13-L22
connect to sql
python
def _connect(self): """Establish connection to MySQL Database.""" if self._connParams: self._conn = MySQLdb.connect(**self._connParams) else: self._conn = MySQLdb.connect('')
https://github.com/aouyar/PyMunin/blob/4f58a64b6b37c85a84cc7e1e07aafaa0321b249d/pysysinfo/mysql.py#L64-L69
connect to sql
python
def connect_database(url): """ create database object by url mysql: mysql+type://user:passwd@host:port/database sqlite: # relative path sqlite+type:///path/to/database.db # absolute path sqlite+type:////path/to/database.db # memory database sqlite+type:// mongodb: mongodb+type://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]] more: http://docs.mongodb.org/manual/reference/connection-string/ sqlalchemy: sqlalchemy+postgresql+type://user:passwd@host:port/database sqlalchemy+mysql+mysqlconnector+type://user:passwd@host:port/database more: http://docs.sqlalchemy.org/en/rel_0_9/core/engines.html redis: redis+taskdb://host:port/db elasticsearch: elasticsearch+type://host:port/?index=pyspider local: local+projectdb://filepath,filepath type: taskdb projectdb resultdb """ db = _connect_database(url) db.copy = lambda: _connect_database(url) return db
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/database/__init__.py#L11-L46
connect to sql
python
def connection_dsn(self, name=None): """ Provides a connection string for database. Parameters ---------- name: str, optional an override database name for the connection string. Returns ------- str: the connection string (e.g. 'dbname=db1 user=user1 host=localhost port=5432') """ return ' '.join("%s=%s" % (param, value) for param, value in self._connect_options(name))
https://github.com/drkjam/pydba/blob/986c4b1315d6b128947c3bc3494513d8e5380ff0/pydba/postgres.py#L243-L256
connect to sql
python
def _connect_db(self): """ Open database connection """ # Get database configuration db_args = {} db_args['host'] = self._cfg.get('nipapd', 'db_host') db_args['database'] = self._cfg.get('nipapd', 'db_name') db_args['user'] = self._cfg.get('nipapd', 'db_user') db_args['password'] = self._cfg.get('nipapd', 'db_pass') db_args['sslmode'] = self._cfg.get('nipapd', 'db_sslmode') db_args['port'] = self._cfg.get('nipapd', 'db_port') # delete keys that are None, for example if we want to connect over a # UNIX socket, the 'host' argument should not be passed into the DSN if db_args['host'] is not None and db_args['host'] == '': db_args['host'] = None for key in db_args.copy(): if db_args[key] is None: del(db_args[key]) # Create database connection while True: try: self._con_pg = psycopg2.connect(**db_args) self._con_pg.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT) self._curs_pg = self._con_pg.cursor(cursor_factory=psycopg2.extras.DictCursor) self._register_inet() psycopg2.extras.register_hstore(self._con_pg, globally=True, unicode=True) except psycopg2.Error as exc: if re.search("database.*does not exist", unicode(exc)): raise NipapDatabaseNonExistentError("Database '%s' does not exist" % db_args['database']) # no hstore extension, assume empty db (it wouldn't work # otherwise) and do auto upgrade? if re.search("hstore type not found in the database", unicode(exc)): # automatically install if auto-install is enabled if self._auto_install_db: self._db_install(db_args['database']) continue raise NipapDatabaseMissingExtensionError("hstore extension not found in the database") self._logger.error("pgsql: %s" % exc) raise NipapError("Backend unable to connect to database") except psycopg2.Warning as warn: self._logger.warning('pgsql: %s' % warn) # check db version try: current_db_version = self._get_db_version() except NipapDatabaseNoVersionError as exc: # if there's no db schema version we assume the database is # empty... if self._auto_install_db: # automatically install schema? self._db_install(db_args['database']) continue raise exc except NipapError as exc: self._logger.error(unicode(exc)) raise exc if current_db_version != nipap.__db_version__: if self._auto_upgrade_db: self._db_upgrade(db_args['database']) continue raise NipapDatabaseWrongVersionError("NIPAP PostgreSQL database is outdated. Schema version %s is required to run but you are using %s" % (nipap.__db_version__, current_db_version)) # if we reach this we should be fine and done break
https://github.com/SpriteLink/NIPAP/blob/f96069f11ab952d80b13cab06e0528f2d24b3de9/nipap/nipap/backend.py#L750-L817
connect to sql
python
def _connect(self): """Try to connect to the database. Raises: :exc:`~ConnectionError`: If the connection to the database fails. :exc:`~AuthenticationError`: If there is a OperationFailure due to Authentication failure after connecting to the database. :exc:`~ConfigurationError`: If there is a ConfigurationError while connecting to the database. """ try: # FYI: the connection process might raise a # `ServerSelectionTimeoutError`, that is a subclass of # `ConnectionFailure`. # The presence of ca_cert, certfile, keyfile, crlfile implies the # use of certificates for TLS connectivity. if self.ca_cert is None or self.certfile is None or \ self.keyfile is None or self.crlfile is None: client = pymongo.MongoClient(self.host, self.port, replicaset=self.replicaset, serverselectiontimeoutms=self.connection_timeout, ssl=self.ssl, **MONGO_OPTS) if self.login is not None and self.password is not None: client[self.dbname].authenticate(self.login, self.password) else: logger.info('Connecting to MongoDB over TLS/SSL...') client = pymongo.MongoClient(self.host, self.port, replicaset=self.replicaset, serverselectiontimeoutms=self.connection_timeout, ssl=self.ssl, ssl_ca_certs=self.ca_cert, ssl_certfile=self.certfile, ssl_keyfile=self.keyfile, ssl_pem_passphrase=self.keyfile_passphrase, ssl_crlfile=self.crlfile, ssl_cert_reqs=CERT_REQUIRED, **MONGO_OPTS) if self.login is not None: client[self.dbname].authenticate(self.login, mechanism='MONGODB-X509') return client except (pymongo.errors.ConnectionFailure, pymongo.errors.OperationFailure) as exc: logger.info('Exception in _connect(): {}'.format(exc)) raise ConnectionError(str(exc)) from exc except pymongo.errors.ConfigurationError as exc: raise ConfigurationError from exc
https://github.com/bigchaindb/bigchaindb/blob/835fdfcf598918f76139e3b88ee33dd157acaaa7/bigchaindb/backend/localmongodb/connection.py#L77-L130
connect to sql
python
def cache_connect(database=None): """Returns a connection object to a sqlite database. Args: database (str, optional): The path to the database the user wishes to connect to. If not specified, a default is chosen using :func:`.cache_file`. If the special database name ':memory:' is given, then a temporary database is created in memory. Returns: :class:`sqlite3.Connection` """ if database is None: database = cache_file() if os.path.isfile(database): # just connect to the database as-is conn = sqlite3.connect(database) else: # we need to populate the database conn = sqlite3.connect(database) conn.executescript(schema) with conn as cur: # turn on foreign keys, allows deletes to cascade. cur.execute("PRAGMA foreign_keys = ON;") conn.row_factory = sqlite3.Row return conn
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/system/cache/database_manager.py#L37-L67
connect to sql
python
def _get_db_connect(dbSystem,db,user,password): """Create a connection to the database specified on the command line """ 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
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/webCat/MOPdbaccess.py#L73-L95
connect to sql
python
def connect(self, **kwargs): ''' Connect to a SQLite instance **Configuration Parameters** database The database name or file to "connect" to. Defaults to **ait**. ''' if 'database' not in kwargs: kwargs['database'] = 'ait' self._conn = self._backend.connect(kwargs['database'])
https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/db.py#L434-L445
connect to sql
python
def connect(self, database_path, mode="a"): """ Connect to a SQLite database. :param str database_path: Path to the SQLite database file to be connected. :param str mode: ``"r"``: Open for read only. ``"w"``: Open for read/write. Delete existing tables when connecting. ``"a"``: Open for read/write. Append to the existing tables. :raises ValueError: If ``database_path`` is invalid or |attr_mode| is invalid. :raises simplesqlite.DatabaseError: If the file is encrypted or is not a database. :raises simplesqlite.OperationalError: If unable to open the database file. """ self.close() logger.debug("connect to a SQLite database: path='{}', mode={}".format(database_path, mode)) if mode == "r": self.__verify_db_file_existence(database_path) elif mode in ["w", "a"]: self.__validate_db_path(database_path) else: raise ValueError("unknown connection mode: " + mode) if database_path == MEMORY_DB_NAME: self.__database_path = database_path else: self.__database_path = os.path.realpath(database_path) try: self.__connection = sqlite3.connect(database_path) except sqlite3.OperationalError as e: raise OperationalError(e) self.__mode = mode try: # validate connection after connect self.fetch_table_names() except sqlite3.DatabaseError as e: raise DatabaseError(e) if mode != "w": return for table in self.fetch_table_names(): self.drop_table(table)
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/core.py#L216-L268
connect to sql
python
def _connect(self): """Try to create a connection to the database if not yet connected. """ if self._connection is not None: raise RuntimeError('Close connection first.') self._connection = connect(self._database, **self._kwds) self._connection.isolation_level = None
https://github.com/merry-bits/DBQuery/blob/5f46dc94e2721129f8a799b5f613373e6cd9cb73/src/dbquery/sqlite.py#L27-L33
connect to sql
python
def connect(cls, database: str, user: str, password: str, host: str, port: int, *, use_pool: bool=True, enable_ssl: bool=False, minsize=1, maxsize=50, keepalives_idle=5, keepalives_interval=4, echo=False, **kwargs): """ Sets connection parameters For more information on the parameters that is accepts, see : http://www.postgresql.org/docs/9.2/static/libpq-connect.html """ cls._connection_params['database'] = database cls._connection_params['user'] = user cls._connection_params['password'] = password cls._connection_params['host'] = host cls._connection_params['port'] = port cls._connection_params['sslmode'] = 'prefer' if enable_ssl else 'disable' cls._connection_params['minsize'] = minsize cls._connection_params['maxsize'] = maxsize cls._connection_params['keepalives_idle'] = keepalives_idle cls._connection_params['keepalives_interval'] = keepalives_interval cls._connection_params['echo'] = echo cls._connection_params.update(kwargs) cls._use_pool = use_pool
https://github.com/nerandell/cauldron/blob/d363bac763781bb2da18debfa0fdd4be28288b92/cauldron/sql.py#L130-L150
connect to sql
python
def connect_db(Repo, database=":memory:"): """ Connect Repo to a database with path +database+ so all instances can interact with the database. """ Repo.db = sqlite3.connect(database, detect_types=sqlite3.PARSE_DECLTYPES) return Repo.db
https://github.com/ECESeniorDesign/lazy_record/blob/929d3cc7c2538b0f792365c0d2b0e0d41084c2dd/lazy_record/repo.py#L294-L301
connect to sql
python
def database(self, name=None): """Connect to a database called `name`. Parameters ---------- name : str, optional The name of the database to connect to. If ``None``, return the database named ``self.current_database``. Returns ------- db : MySQLDatabase An :class:`ibis.sql.mysql.client.MySQLDatabase` instance. Notes ----- This creates a new connection if `name` is both not ``None`` and not equal to the current database. """ if name == self.current_database or ( name is None and name != self.current_database ): return self.database_class(self.current_database, self) else: url = self.con.url client_class = type(self) new_client = client_class( host=url.host, user=url.username, port=url.port, password=url.password, database=name, ) return self.database_class(name, new_client)
https://github.com/ibis-project/ibis/blob/1e39a5fd9ef088b45c155e8a5f541767ee8ef2e7/ibis/sql/mysql/client.py#L108-L141
connect to sql
python
def reconnect(self, query = None, log_reconnect = False): """ Reconnect to the database. """ uri = list(urisup.uri_help_split(self.sqluri)) if uri[1]: authority = list(uri[1]) if authority[1]: authority[1] = None uri[1] = authority if log_reconnect: LOG.warning('reconnecting to %r database (query: %r)', urisup.uri_help_unsplit(uri), query) self.__connect()
https://github.com/decryptus/sonicprobe/blob/72f73f3a40d2982d79ad68686e36aa31d94b76f8/sonicprobe/libs/anysql.py#L374-L387
connect to sql
python
def connect(db='', **kwargs): """ db 접속 공통 인자들 채워서 접속, schema만 넣으면 됩니다. db connection 객체 반환이지만 with 문과 같이 쓰이면 cursor임에 주의 (MySQLdb의 구현이 그렇습니다.) ex1) import snipy.database as db conn = db.connect('my_db') cursor = conn.cursor() ex2) import snipy.database as db with db.connect('my_db') as cursor: cursor.execute(query) :param db: str: db schema :param kwargs: 추가 접속 정보 :return: connection or cursor """ arg = db_config(db) arg.update(kwargs) return MySQLdb.connect(**arg)
https://github.com/dade-ai/snipy/blob/408520867179f99b3158b57520e2619f3fecd69b/snipy/database.py#L41-L62
connect to sql
python
def connection(self): """Attempts to connect to the MySQL server. :return: Bound MySQL connection object if successful or ``None`` if unsuccessful. """ ctx = _app_ctx_stack.top if ctx is not None: if not hasattr(ctx, 'mysql_db'): ctx.mysql_db = self.connect return ctx.mysql_db
https://github.com/admiralobvious/flask-mysqldb/blob/418c794e9b031addd026f29312865403baea55a0/flask_mysqldb/__init__.py#L84-L95
connect to sql
python
def _get_connection(self): """ Returns connection to sqlite db. Returns: connection to the sqlite db who stores mpr data. """ if getattr(self, '_connection', None): logger.debug('Connection to sqlite db already exists. Using existing one.') else: dsn = self._dsn if dsn == 'sqlite://': dsn = ':memory:' else: dsn = dsn.replace('sqlite:///', '') logger.debug( 'Creating new apsw connection.\n dsn: {}, config_dsn: {}' .format(dsn, self._dsn)) self._connection = apsw.Connection(dsn) return self._connection
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/mprlib/backends/sqlite.py#L273-L294
connect to sql
python
def connect(self): """ Connects to the SSDB server if not already connected """ if self._sock: return try: sock = self._connect() except socket.error: e = sys.exc_info()[1] raise ConnectionError(self._error_message(e)) self._sock = sock try: self.on_connect() except SSDBError: # clean up after any error in on_connect self.disconnect() raise # run any user callbacks. right now the only internal callback # is for pubsub channel/pattern resubscription for callback in self._connect_callbacks: callback(self)
https://github.com/wrongwaycn/ssdb-py/blob/ce7b1542f0faa06fe71a60c667fe15992af0f621/ssdb/connection.py#L274-L297
connect to sql
python
def connect_to_database_odbc_sqlserver(self, odbc_connection_string: str = None, dsn: str = None, database: str = None, user: str = None, password: str = None, server: str = "localhost", driver: str = "{SQL Server}", autocommit: bool = True) -> None: """Connects to an SQL Server database via ODBC.""" self.connect(engine=ENGINE_SQLSERVER, interface=INTERFACE_ODBC, odbc_connection_string=odbc_connection_string, dsn=dsn, database=database, user=user, password=password, host=server, driver=driver, autocommit=autocommit)
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L1983-L1998
connect to sql
python
def connect(self): """Initialize connection to the nsqd.""" if self.state == DISCONNECTED: raise errors.NSQException('connection already closed') if self.is_connected: return stream = Stream(self.address, self.port, self.timeout) stream.connect() self.stream = stream self.state = CONNECTED self.send(nsq.MAGIC_V2)
https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/nsqd.py#L205-L218
connect to sql
python
def connect(self, *args, **kwargs): """ Connect to a sqlite database only if no connection exists. Isolation level for the connection is automatically set to autocommit """ self.db = sqlite3.connect(*args, **kwargs) self.db.isolation_level = None
https://github.com/shaunduncan/nosqlite/blob/3033c029b7c8290c66a8b36dc512e560505d4c85/nosqlite.py#L30-L36
connect to sql
python
def _connect(self): """Connects via SSH. """ ssh = self._ssh_client() logger.debug("Connecting with %s", ', '.join('%s=%r' % (k, v if k != "password" else "***") for k, v in iteritems(self.destination))) ssh.connect(**self.destination) logger.debug("Connected to %s", self.destination['hostname']) self._ssh = ssh
https://github.com/VisTrails/tej/blob/b8dedaeb6bdeb650b46cfe6d85e5aa9284fc7f0b/tej/submission.py#L209-L218
connect to sql
python
def connect(self, fn): """SQLite connect method initialize db""" self.conn = sqlite3.connect(fn) cur = self.get_cursor() cur.execute('PRAGMA page_size=4096') cur.execute('PRAGMA FOREIGN_KEYS=ON') cur.execute('PRAGMA cache_size=10000') cur.execute('PRAGMA journal_mode=MEMORY')
https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/lookups/sqlite/base.py#L384-L391
connect to sql
python
def connect(self, name): """Generic database. Opens the SQLite database with the given name. The .db extension is automatically appended to the name. For each table in the database an attribute is created, and assigned a Table object. You can do: database.table or database[table]. """ self._name = name.rstrip(".db") self._con = sqlite.connect(self._name + ".db") self._cur = self._con.cursor() self._tables = [] self._cur.execute("select name from sqlite_master where type='table'") for r in self._cur: self._tables.append(r[0]) self._indices = [] self._cur.execute("select name from sqlite_master where type='index'") for r in self._cur: self._indices.append(r[0]) for t in self._tables: self._cur.execute("pragma table_info("+t+")") fields = [] key = "" for r in self._cur: fields.append(r[1]) if r[2] == "integer": key = r[1] setattr(self, t, Table(self, t, key, fields))
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/database/__init__.py#L31-L63
connect to sql
python
def connect(self): """Initialize the database connection.""" self._client = self._create_client() self._db = getattr(self._client, self._db_name) self._generic_dao = GenericDAO(self._client, self._db_name)
https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/data/pymongo/mongodb.py#L44-L48
connect to sql
python
def db_connect(connection_string=None, **kwargs): """Function to supply a database connection object.""" if connection_string is None: connection_string = get_current_registry().settings[CONNECTION_STRING] db_conn = psycopg2.connect(connection_string, **kwargs) try: with db_conn: yield db_conn finally: db_conn.close()
https://github.com/openstax/cnx-publishing/blob/f55b4a2c45d8618737288f1b74b4139d5ac74154/cnxpublishing/db.py#L49-L58
connect to sql
python
def connection_url(self, name=None): """ Provides a connection string for database as a sqlalchemy compatible URL. NB - this doesn't include special arguments related to SSL connectivity (which are outside the scope of the connection URL format). Parameters ---------- name: str, optional an override database name for the connection string. Returns ------- str: the connection URL (e.g. postgresql://user1@localhost:5432/db1) """ return 'postgresql://{user}@{host}:{port}/{dbname}'.format(**{k: v for k, v in self._connect_options(name)})
https://github.com/drkjam/pydba/blob/986c4b1315d6b128947c3bc3494513d8e5380ff0/pydba/postgres.py#L258-L274
connect to sql
python
def connect(self): """Try to connect to the database. Raises: :exc:`~ConnectionError`: If the connection to the database fails. """ attempt = 0 for i in self.max_tries_counter: attempt += 1 try: self._conn = self._connect() except ConnectionError as exc: logger.warning('Attempt %s/%s. Connection to %s:%s failed after %sms.', attempt, self.max_tries if self.max_tries != 0 else '∞', self.host, self.port, self.connection_timeout) if attempt == self.max_tries: logger.critical('Cannot connect to the Database. Giving up.') raise ConnectionError() from exc else: break
https://github.com/bigchaindb/bigchaindb/blob/835fdfcf598918f76139e3b88ee33dd157acaaa7/bigchaindb/backend/connection.py#L148-L169
connect to sql
python
def connect_db(config): """Connects to the specific database.""" rv = sqlite3.connect(config["database"]["uri"]) rv.row_factory = sqlite3.Row return rv
https://github.com/Julian/Minion/blob/518d06f9ffd38dcacc0de4d94e72d1f8452157a8/examples/flaskr.py#L92-L96
connect to sql
python
def connect(dbapi_connection, connection_record): """ Called once by SQLAlchemy for each new SQLite DB-API connection. Here is where we issue some PRAGMA statements to configure how we're going to access the SQLite database. @param dbapi_connection: A newly connected raw SQLite DB-API connection. @param connection_record: Unused by this method. """ try: cursor = dbapi_connection.cursor() try: cursor.execute("PRAGMA foreign_keys = ON;") cursor.execute("PRAGMA foreign_keys;") if cursor.fetchone()[0] != 1: raise Exception() finally: cursor.close() except Exception: dbapi_connection.close() raise sqlite3.Error()
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/sql.py#L101-L125
connect to sql
python
def _connect(dbfile: 'PathLike') -> apsw.Connection: """Connect to SQLite database file.""" conn = apsw.Connection(os.fspath(dbfile)) _set_foreign_keys(conn, 1) assert _get_foreign_keys(conn) == 1 return conn
https://github.com/darkfeline/animanager/blob/55d92e4cbdc12aac8ebe302420d2cff3fa9fa148/animanager/animecmd.py#L127-L132
connect to sql
python
async def on_connect(self): """ Initialize the connection, authenticate and select a database and send READONLY if it is set during object initialization. """ if self.db: warnings.warn('SELECT DB is not allowed in cluster mode') self.db = '' await super(ClusterConnection, self).on_connect() if self.readonly: await self.send_command('READONLY') if nativestr(await self.read_response()) != 'OK': raise ConnectionError('READONLY command failed')
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/connection.py#L651-L663
connect to sql
python
def _reconnect(self): """Closes the existing database connection and re-opens it.""" self.close() self._db = psycopg2.connect(**self._db_args) if self._search_path: self.execute('set search_path=%s;' % self._search_path) if self._timezone: self.execute("set timezone='%s';" % self._timezone)
https://github.com/stevepeak/tornpsql/blob/a109d0f95d6432d0e3b5eba1c9854357ba527f27/tornpsql/__init__.py#L134-L143
connect to sql
python
def execute_sql(self, sql, commit=False): """Log and then execute a SQL query""" logger.info("Running sqlite query: \"%s\"", sql) self.connection.execute(sql) if commit: self.connection.commit()
https://github.com/openvax/datacache/blob/73bcac02d37cf153710a07fbdc636aa55cb214ca/datacache/database.py#L66-L71
connect to sql
python
def s_connect(self, server, port, r_server=None): """ Link a server. Required arguments: * server - Server to link with. * port - Port to use. Optional arguments: * r_server=None - Link r_server with server. """ with self.lock: if not r_server: self.send('CONNECT %s %s' % (server, port), error_check=True) else: self.send('CONNECT %s %s %s' % (server, port, \ r_server), error_check=True)
https://github.com/jamieleshaw/lurklib/blob/a861f35d880140422103dd78ec3239814e85fd7e/lurklib/squeries.py#L192-L206
connect to sql
python
def reconnect(self): """Closes the existing database connection and re-opens it.""" conn = _mysql.connect(**self._db_args) if conn is not None: self.close() self._db = conn
https://github.com/memsql/memsql-python/blob/aac223a1b937d5b348b42af3c601a6c685ca633a/memsql/common/database.py#L95-L100
connect to sql
python
def connect(dsn=None, database=None, user=None, password=None, timeout=None, login_timeout=15, as_dict=None, appname=None, port=None, tds_version=tds_base.TDS74, autocommit=False, blocksize=4096, use_mars=False, auth=None, readonly=False, load_balancer=None, use_tz=None, bytes_to_unicode=True, row_strategy=None, failover_partner=None, server=None, cafile=None, validate_host=True, enc_login_only=False, disable_connect_retry=False, pooling=False, ): """ Opens connection to the database :keyword dsn: SQL server host and instance: <host>[\<instance>] :type dsn: string :keyword failover_partner: secondary database host, used if primary is not accessible :type failover_partner: string :keyword database: the database to initially connect to :type database: string :keyword user: database user to connect as :type user: string :keyword password: user's password :type password: string :keyword timeout: query timeout in seconds, default 0 (no timeout) :type timeout: int :keyword login_timeout: timeout for connection and login in seconds, default 15 :type login_timeout: int :keyword as_dict: whether rows should be returned as dictionaries instead of tuples. :type as_dict: boolean :keyword appname: Set the application name to use for the connection :type appname: string :keyword port: the TCP port to use to connect to the server :type port: int :keyword tds_version: Maximum TDS version to use, should only be used for testing :type tds_version: int :keyword autocommit: Enable or disable database level autocommit :type autocommit: bool :keyword blocksize: Size of block for the TDS protocol, usually should not be used :type blocksize: int :keyword use_mars: Enable or disable MARS :type use_mars: bool :keyword auth: An instance of authentication method class, e.g. Ntlm or Sspi :keyword readonly: Allows to enable read-only mode for connection, only supported by MSSQL 2012, earlier versions will ignore this parameter :type readonly: bool :keyword load_balancer: An instance of load balancer class to use, if not provided will not use load balancer :keyword use_tz: Provides timezone for naive database times, if not provided date and time will be returned in naive format :keyword bytes_to_unicode: If true single byte database strings will be converted to unicode Python strings, otherwise will return strings as ``bytes`` without conversion. :type bytes_to_unicode: bool :keyword row_strategy: strategy used to create rows, determines type of returned rows, can be custom or one of: :func:`tuple_row_strategy`, :func:`list_row_strategy`, :func:`dict_row_strategy`, :func:`namedtuple_row_strategy`, :func:`recordtype_row_strategy` :type row_strategy: function of list of column names returning row factory :keyword cafile: Name of the file containing trusted CAs in PEM format, if provided will enable TLS :type cafile: str :keyword validate_host: Host name validation during TLS connection is enabled by default, if you disable it you will be vulnerable to MitM type of attack. :type validate_host: bool :keyword enc_login_only: Allows you to scope TLS encryption only to an authentication portion. This means that anyone who can observe traffic on your network will be able to see all your SQL requests and potentially modify them. :type enc_login_only: bool :returns: An instance of :class:`Connection` """ login = _TdsLogin() login.client_host_name = socket.gethostname()[:128] login.library = "Python TDS Library" login.user_name = user or '' login.password = password or '' login.app_name = appname or 'pytds' login.port = port login.language = '' # use database default login.attach_db_file = '' login.tds_version = tds_version if tds_version < tds_base.TDS70: raise ValueError('This TDS version is not supported') login.database = database or '' login.bulk_copy = False login.client_lcid = lcid.LANGID_ENGLISH_US login.use_mars = use_mars login.pid = os.getpid() login.change_password = '' login.client_id = uuid.getnode() # client mac address login.cafile = cafile login.validate_host = validate_host login.enc_login_only = enc_login_only if cafile: if not tls.OPENSSL_AVAILABLE: raise ValueError("You are trying to use encryption but pyOpenSSL does not work, you probably " "need to install it first") login.tls_ctx = tls.create_context(cafile) if login.enc_login_only: login.enc_flag = PreLoginEnc.ENCRYPT_OFF else: login.enc_flag = PreLoginEnc.ENCRYPT_ON else: login.tls_ctx = None login.enc_flag = PreLoginEnc.ENCRYPT_NOT_SUP if use_tz: login.client_tz = use_tz else: login.client_tz = pytds.tz.local # that will set: # ANSI_DEFAULTS to ON, # IMPLICIT_TRANSACTIONS to OFF, # TEXTSIZE to 0x7FFFFFFF (2GB) (TDS 7.2 and below), TEXTSIZE to infinite (introduced in TDS 7.3), # and ROWCOUNT to infinite login.option_flag2 = tds_base.TDS_ODBC_ON login.connect_timeout = login_timeout login.query_timeout = timeout login.blocksize = blocksize login.auth = auth login.readonly = readonly login.load_balancer = load_balancer login.bytes_to_unicode = bytes_to_unicode if server and dsn: raise ValueError("Both server and dsn shouldn't be specified") if server: warnings.warn("server parameter is deprecated, use dsn instead", DeprecationWarning) dsn = server if load_balancer and failover_partner: raise ValueError("Both load_balancer and failover_partner shoudln't be specified") if load_balancer: servers = [(srv, None) for srv in load_balancer.choose()] else: servers = [(dsn or 'localhost', port)] if failover_partner: servers.append((failover_partner, port)) parsed_servers = [] for srv, port in servers: host, instance = _parse_server(srv) if instance and port: raise ValueError("Both instance and port shouldn't be specified") parsed_servers.append((host, port, instance)) login.servers = _get_servers_deque(tuple(parsed_servers), database) # unique connection identifier used to pool connection key = ( dsn, login.user_name, login.app_name, login.tds_version, login.database, login.client_lcid, login.use_mars, login.cafile, login.blocksize, login.readonly, login.bytes_to_unicode, login.auth, login.client_tz, autocommit, ) conn = Connection() conn._use_tz = use_tz conn._autocommit = autocommit conn._login = login conn._pooling = pooling conn._key = key assert row_strategy is None or as_dict is None,\ 'Both row_startegy and as_dict were specified, you should use either one or another' if as_dict is not None: conn.as_dict = as_dict elif row_strategy is not None: conn._row_strategy = row_strategy else: conn._row_strategy = tuple_row_strategy # default row strategy conn._isolation_level = 0 conn._dirty = False from .tz import FixedOffsetTimezone conn._tzinfo_factory = None if use_tz is None else FixedOffsetTimezone if disable_connect_retry: conn._try_open(timeout=login.connect_timeout) else: conn._open() return conn
https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/__init__.py#L1142-L1331
connect to sql
python
def connect(self): """connect to the database **Return:** - ``dbConn`` -- the database connection See the class docstring for usage """ self.log.debug('starting the ``get`` method') dbSettings = self.dbSettings port = False if "tunnel" in dbSettings and dbSettings["tunnel"]: port = self._setup_tunnel( tunnelParameters=dbSettings["tunnel"] ) # SETUP A DATABASE CONNECTION host = dbSettings["host"] user = dbSettings["user"] passwd = dbSettings["password"] dbName = dbSettings["db"] dbConn = ms.connect( host=host, user=user, passwd=passwd, db=dbName, port=port, use_unicode=True, charset='utf8', local_infile=1, client_flag=ms.constants.CLIENT.MULTI_STATEMENTS, connect_timeout=36000, max_allowed_packet=51200000 ) if self.autocommit: dbConn.autocommit(True) self.log.debug('completed the ``get`` method') return dbConn
https://github.com/thespacedoctor/fundamentals/blob/1d2c007ac74442ec2eabde771cfcacdb9c1ab382/fundamentals/mysql/database.py#L85-L125
connect to sql
python
def get_mysql_connection(host, user, port, password, database, ssl={}): """ MySQL connection """ return pymysql.connect(host=host, user=user, port=port, password=password, db=database, charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor, client_flag=pymysql.constants.CLIENT.MULTI_STATEMENTS, ssl=ssl )
https://github.com/gabfl/dbschema/blob/37722e6654e9f0374fac5518ebdca22f4c39f92f/src/schema_change.py#L94-L106
connect to sql
python
def add_query(self, sql, auto_begin=True, bindings=None, abridge_sql_log=False): """Add a query to the current transaction. A thin wrapper around ConnectionManager.add_query. :param str sql: The SQL query to add :param bool auto_begin: If set and there is no transaction in progress, begin a new one. :param Optional[List[object]]: An optional list of bindings for the query. :param bool abridge_sql_log: If set, limit the raw sql logged to 512 characters """ return self.connections.add_query(sql, auto_begin, bindings, abridge_sql_log)
https://github.com/fishtown-analytics/dbt/blob/aa4f771df28b307af0cf9fe2fc24432f10a8236b/core/dbt/adapters/sql/impl.py#L39-L53
connect to sql
python
def connect(path, lock_transactions=True, lock_timeout=-1, single_cursor_mode=False, factory=Connection, *args, **kwargs): """Analogous to sqlite3.connect() :param path: Path to the database :param lock_transactions: If `True`, parallel transactions will be blocked :param lock_timeout: Maximum amount of time the connection is allowed to wait for a lock. If the timeout i exceeded, :any:`LockTimeoutError` will be thrown. -1 disables the timeout. :param single_cursor_mode: Use only one cursor (default: `False`) :param factory: Connection class (default: :any:`Connection`) """ return factory(path, lock_transactions=lock_transactions, lock_timeout=lock_timeout, single_cursor_mode=single_cursor_mode, *args, **kwargs)
https://github.com/ivknv/s3m/blob/71663c12613d41cf7d3dd99c819d50a7c1b7ff9d/s3m.py#L622-L639
connect to sql
python
def query(querystr, connection=None, **connectkwargs): """Execute a query of the given SQL database """ if connection is None: connection = connect(**connectkwargs) cursor = connection.cursor() cursor.execute(querystr) return cursor.fetchall()
https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/table/io/hacr.py#L151-L158
connect to sql
python
def database(self, name=None): """Connect to a database called `name`. Parameters ---------- name : str, optional The name of the database to connect to. If ``None``, return the database named ``self.current_database``. Returns ------- db : Database An :class:`ibis.client.Database` instance. Notes ----- This creates a new connection if `name` is both not ``None`` and not equal to the current database. """ if name == self.current_database or name is None: return self.database_class(self.current_database, self) else: client_class = type(self) new_client = client_class( uri=self.uri, user=self.user, password=self.password, host=self.host, port=self.port, database=name, protocol=self.protocol, execution_type=self.execution_type, ) return self.database_class(name, new_client)
https://github.com/ibis-project/ibis/blob/1e39a5fd9ef088b45c155e8a5f541767ee8ef2e7/ibis/mapd/client.py#L693-L726
connect to sql
python
def connect(self, dsn): """Connect to DB. dbname: the database name user: user name used to authenticate password: password used to authenticate host: database host address (defaults to UNIX socket if not provided) port: connection port number (defaults to 5432 if not provided) """ self.con = psycopg2.connect(dsn) self.cur = self.con.cursor(cursor_factory=psycopg2.extras.DictCursor) # autocommit: Disable automatic transactions self.con.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/management/commands/util/util.py#L114-L126
connect to sql
python
def set_mysql_connection(host='localhost', user='pyctd_user', password='pyctd_passwd', db='pyctd', charset='utf8'): """Sets the connection using MySQL Parameters""" set_connection('mysql+pymysql://{user}:{passwd}@{host}/{db}?charset={charset}'.format( host=host, user=user, passwd=password, db=db, charset=charset) )
https://github.com/cebel/pyctd/blob/38ba02adaddb60cef031d3b75516773fe8a046b5/src/pyctd/manager/database.py#L454-L462
connect to sql
python
def connect(self): """obj.connect() => True or raise Error from MySQLdb. You aren't suggested to use this function by your hand, because this func may cause Exception. """ self.conn = self.db_module.connect( host=self.host, port=int(self.port), user=self.user, passwd=self.passwd, db=self.dbname, charset=self.charset, cursorclass=self.cursorclass) self.conn.autocommit(self.autocommit) return True
https://github.com/zagfai/webtul/blob/58c49928070b56ef54a45b4af20d800b269ad8ce/webtul/db.py#L68-L78
connect to sql
python
def connection(self): """Return an SqlAlchemy connection.""" if not self._connection: logger.debug('Opening connection to: {}'.format(self.dsn)) self._connection = self.engine.connect() logger.debug('Opened connection to: {}'.format(self.dsn)) # logger.debug("Opening connection to: {}".format(self.dsn)) return self._connection
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/database.py#L228-L236
connect to sql
python
def connection(self, name=None): """ Get a database connection instance :param name: The connection name :type name: str :return: A Connection instance :rtype: orator.connections.connection.Connection """ name, type = self._parse_connection_name(name) if name not in self._connections: logger.debug("Initiating connection %s" % name) connection = self._make_connection(name) self._set_connection_for_type(connection, type) self._connections[name] = self._prepare(connection) return self._connections[name]
https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/database_manager.py#L28-L48
connect to sql
python
def get_connection(db_type, db_pth, user=None, password=None, name=None): """ Get a connection to a SQL database. Can be used for SQLite, MySQL or Django MySQL database Example: >>> from msp2db.db import get_connection >>> conn = get_connection('sqlite', 'library.db') If using "mysql" mysql.connector needs to be installed. If using "django_mysql" Django needs to be installed. Args: db_type (str): Type of database can either be "sqlite", "mysql" or "django_mysql" Returns: sql connection object """ if db_type == 'sqlite': print(db_pth) conn = sqlite3.connect(db_pth) elif db_type == 'mysql': import mysql.connector conn = mysql.connector.connect(user=user, password=password, database=name) elif db_type == 'django_mysql': from django.db import connection as conn else: print('unsupported database type: {}, choices are "sqlite", "mysql" or "django_mysql"'.format(db_type)) return conn
https://github.com/computational-metabolomics/msp2db/blob/f86f01efca26fd2745547c9993f97337c6bef123/msp2db/db.py#L99-L129
connect to sql
python
def db_connect(cls, path): """ connect to our chainstate db """ con = sqlite3.connect(path, isolation_level=None, timeout=2**30) con.row_factory = StateEngine.db_row_factory return con
https://github.com/blockstack/virtualchain/blob/fcfc970064ca7dfcab26ebd3ab955870a763ea39/virtualchain/lib/indexer.py#L330-L336
connect to sql
python
def initialize_connections(self, scopefunc=None): """ Initialize a database connection by each connection string defined in the configuration file """ for connection_name, connection_string in\ self.app.config['FLASK_PHILO_SQLALCHEMY'].items(): engine = create_engine(connection_string) session = scoped_session(sessionmaker(), scopefunc=scopefunc) session.configure(bind=engine) self.connections[connection_name] = Connection(engine, session)
https://github.com/Riffstation/Flask-Philo-SQLAlchemy/blob/71598bb603b8458a2cf9f7989f71d8f1c77fafb9/flask_philo_sqlalchemy/connection.py#L26-L36
connect to sql
python
def _connect(self): """Establish connection to PostgreSQL Database.""" if self._connParams: self._conn = psycopg2.connect(**self._connParams) else: self._conn = psycopg2.connect('') try: ver_str = self._conn.get_parameter_status('server_version') except AttributeError: ver_str = self.getParam('server_version') self._version = util.SoftwareVersion(ver_str)
https://github.com/aouyar/PyMunin/blob/4f58a64b6b37c85a84cc7e1e07aafaa0321b249d/pysysinfo/postgresql.py#L76-L86
connect to sql
python
def _connect(self, context): """Initialize the database connection.""" if __debug__: log.info("Connecting " + self.engine.partition(':')[0] + " database layer.", extra=dict( uri = redact_uri(self.uri, self.protect), config = self.config, alias = self.alias, )) self.connection = context.db[self.alias] = self._connector(self.uri, **self.config)
https://github.com/marrow/web.db/blob/c755fbff7028a5edc223d6a631b8421858274fc4/web/db/dbapi.py#L42-L52
connect to sql
python
def connect_mysql(host, port, user, password, database): """Connect to MySQL with retries.""" return pymysql.connect( host=host, port=port, user=user, passwd=password, db=database )
https://github.com/openstack/monasca-common/blob/61e2e00454734e2881611abec8df0d85bf7655ac/docker/mysql_check.py#L109-L115
connect to sql
python
def get_connection(db=DATABASE): """ Returns a new connection to the database. """ return database.connect(host=HOST, port=PORT, user=USER, password=PASSWORD, database=db)
https://github.com/memsql/memsql-python/blob/aac223a1b937d5b348b42af3c601a6c685ca633a/examples/multi_threaded_inserts.py#L30-L32
connect to sql
python
def connect( host='localhost', user=None, password=None, port=3306, database=None, url=None, driver='pymysql', ): """Create an Ibis client located at `user`:`password`@`host`:`port` connected to a MySQL database named `database`. Parameters ---------- host : string, default 'localhost' user : string, default None password : string, default None port : string or integer, default 3306 database : string, default None url : string, default None Complete SQLAlchemy connection string. If passed, the other connection arguments are ignored. driver : string, default 'pymysql' Returns ------- MySQLClient Examples -------- >>> import os >>> import getpass >>> host = os.environ.get('IBIS_TEST_MYSQL_HOST', 'localhost') >>> user = os.environ.get('IBIS_TEST_MYSQL_USER', getpass.getuser()) >>> password = os.environ.get('IBIS_TEST_MYSQL_PASSWORD') >>> database = os.environ.get('IBIS_TEST_MYSQL_DATABASE', ... 'ibis_testing') >>> con = connect( ... database=database, ... host=host, ... user=user, ... password=password ... ) >>> con.list_tables() # doctest: +ELLIPSIS [...] >>> t = con.table('functional_alltypes') >>> t MySQLTable[table] name: functional_alltypes schema: index : int64 Unnamed: 0 : int64 id : int32 bool_col : int8 tinyint_col : int8 smallint_col : int16 int_col : int32 bigint_col : int64 float_col : float32 double_col : float64 date_string_col : string string_col : string timestamp_col : timestamp year : int32 month : int32 """ return MySQLClient( host=host, user=user, password=password, port=port, database=database, url=url, driver=driver, )
https://github.com/ibis-project/ibis/blob/1e39a5fd9ef088b45c155e8a5f541767ee8ef2e7/ibis/sql/mysql/api.py#L46-L121
connect to sql
python
def connect(self, **kwargs): ''' Connect to an InfluxDB instance Connects to an InfluxDB instance and switches to a given database. If the database doesn't exist it is created first via :func:`create`. **Configuration Parameters** host The host for the connection. Passed as either the config key **database.host** or the kwargs argument **host**. Defaults to **localhost**. port The port for the connection. Passed as either the config key **database.port** or the kwargs argument **port**. Defaults to **8086**. un The un for the connection. Passed as either the config key **database.un** or the kwargs argument **un**. Defaults to **root**. pw The pw for the connection. Passed as either the config key **database.pw** or the kwargs argument **pw**. Defaults to **pw**. database name The database name for the connection. Passed as either the config key **database.dbname** or the kwargs argument **database**. Defaults to **ait**. ''' host = ait.config.get('database.host', kwargs.get('host', 'localhost')) port = ait.config.get('database.port', kwargs.get('port', 8086)) un = ait.config.get('database.un', kwargs.get('un', 'root')) pw = ait.config.get('database.pw', kwargs.get('pw', 'root')) dbname = ait.config.get('database.dbname', kwargs.get('database', 'ait')) self._conn = self._backend.InfluxDBClient(host, port, un, pw) if dbname not in [v['name'] for v in self._conn.get_list_database()]: self.create(database=dbname) self._conn.switch_database(dbname)
https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/db.py#L221-L265
connect to sql
python
def connect(db_url=None, pooling=hgvs.global_config.uta.pooling, application_name=None, mode=None, cache=None): """Connect to a uta/ncbi database instance. :param db_url: URL for database connection :type db_url: string :param pooling: whether to use connection pooling (postgresql only) :type pooling: bool :param application_name: log application name in connection (useful for debugging; PostgreSQL only) :type application_name: str When called with an explicit db_url argument, that db_url is used for connecting. When called without an explicit argument, the function default is determined by the environment variable UTA_DB_URL if it exists, or hgvs.datainterface.uta.public_db_url otherwise. >>> hdp = connect() >>> hdp.schema_version() '1.1' The format of the db_url is driver://user:pass@host/database (the same as that used by SQLAlchemy). Examples: A remote public postgresql database: postgresql://anonymous:anonymous@uta.biocommons.org/uta' A local postgresql database: postgresql://localhost/uta A local SQLite database: sqlite:////tmp/uta-0.0.6.db For postgresql db_urls, pooling=True causes connect to use a psycopg2.pool.ThreadedConnectionPool. """ _logger.debug('connecting to ' + str(db_url) + '...') if db_url is None: db_url = _get_ncbi_db_url() url = _parse_url(db_url) if url.scheme == 'postgresql': conn = NCBI_postgresql( url=url, pooling=pooling, application_name=application_name, mode=mode, cache=cache) else: # fell through connection scheme cases raise RuntimeError("{url.scheme} in {url} is not currently supported".format(url=url)) _logger.info('connected to ' + str(db_url) + '...') return conn
https://github.com/biocommons/hgvs/blob/4d16efb475e1802b2531a2f1c373e8819d8e533b/hgvs/dataproviders/ncbi.py#L55-L108
connect to sql
python
def open( self ): """Open the database connection.""" if self._connection is None: self._connection = sqlite3.connect(self._dbfile)
https://github.com/simoninireland/epyc/blob/b3b61007741a0ab3de64df89070a6f30de8ec268/epyc/sqlitelabnotebook.py#L58-L61
connect to sql
python
def _open(self, db, writeAccess=False): """ Handles simple, SQL specific connection creation. This will not have to manage thread information as it is already managed within the main open method for the SQLBase class. :param db | <orb.Database> :return <variant> | backend specific database connection """ if not pymysql: raise orb.errors.BackendNotFound('psycopg2 is not installed.') # create the python connection try: return pymysql.connect(db=db.name(), user=db.username(), passwd=db.password(), host=(db.writeHost() if writeAccess else db.host()) or 'localhost', port=db.port() or 3306, cursorclass=pymysql.cursors.DictCursor) except pymysql.OperationalError as err: log.exception('Failed to connect to postgres') raise orb.errors.ConnectionFailed()
https://github.com/orb-framework/orb/blob/575be2689cb269e65a0a2678232ff940acc19e5a/orb/core/connection_types/sql/mysql/mysqlconnection.py#L107-L130
connect to sql
python
def set_mysql_connection(host='localhost', user='pyhgnc_user', passwd='pyhgnc_passwd', db='pyhgnc', charset='utf8'): """Method to set a MySQL connection :param str host: MySQL database host :param str user: MySQL database user :param str passwd: MySQL database password :param str db: MySQL database name :param str charset: MySQL database charater set :return: connection string :rtype: str """ connection_string = 'mysql+pymysql://{user}:{passwd}@{host}/{db}?charset={charset}'.format( host=host, user=user, passwd=passwd, db=db, charset=charset ) set_connection(connection_string) return connection_string
https://github.com/LeKono/pyhgnc/blob/1cae20c40874bfb51581b7c5c1481707e942b5d0/src/pyhgnc/manager/database.py#L467-L489
connect to sql
python
def connect(host=None, database=None, user=None, password=None, **kwargs): """Create a database connection.""" host = host or os.environ['PGHOST'] database = database or os.environ['PGDATABASE'] user = user or os.environ['PGUSER'] password = password or os.environ['PGPASSWORD'] return psycopg2.connect(host=host, database=database, user=user, password=password, **kwargs)
https://github.com/portfoliome/postpy/blob/fe26199131b15295fc5f669a0ad2a7f47bf490ee/postpy/connections.py#L8-L20
connect to sql
python
def db_connect(engine, schema=None, clobber=False): """Create a connection object to a database. Attempt to establish a schema. If there are existing tables, delete them if clobber is True and return otherwise. Returns a sqlalchemy engine object. """ 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
https://github.com/fhcrc/taxtastic/blob/4e874b7f2cc146178828bfba386314f8c342722b/taxtastic/ncbi.py#L215-L240
connect to sql
python
def run_sql_query(self, sql, required=False, query_params=[]): """ Given an arbitrary SQL query, run it against the database and return the results. Parameters ---------- sql : str SQL query required : bool Raise an error if no results found in the database query_params : list For each '?' in the query there must be a corresponding value in this list. """ try: cursor = self.connection.execute(sql, query_params) except sqlite3.OperationalError as e: error_message = e.message if hasattr(e, 'message') else str(e) logger.warn( "Encountered error \"%s\" from query \"%s\" with parameters %s", error_message, sql, query_params) raise results = cursor.fetchall() if required and not results: raise ValueError( "No results found for query:\n%s\nwith parameters: %s" % ( sql, query_params)) return results
https://github.com/openvax/pyensembl/blob/4b995fb72e848206d6fbf11950cf30964cd9b3aa/pyensembl/database.py#L412-L445
connect to sql
python
def _connection(username=None, password=None, host=None, port=None): "returns a connected cursor to the database-server." c_opts = {} if username: c_opts['user'] = username if password: c_opts['passwd'] = password if host: c_opts['host'] = host if port: c_opts['port'] = port dbc = MySQLdb.connect(**c_opts) dbc.autocommit(True) return dbc
https://github.com/bmaeser/pyque/blob/856dceab8d89cf3771cf21e682466c29a85ae8eb/pyque/db/mysql.py#L37-L49
connect to sql
python
def get_connection(self): """Get a connection to this Database. Connections are retrieved from a pool. """ if not self.open: raise exc.ResourceClosedError('Database closed.') return Connection(self._engine.connect())
https://github.com/kennethreitz/records/blob/ecd857266c5e7830d657cbe0196816314790563b/records.py#L285-L292
connect to sql
python
def ping(self) -> None: """Pings a database connection, reconnecting if necessary.""" if self.db is None or self.db_pythonlib not in [PYTHONLIB_MYSQLDB, PYTHONLIB_PYMYSQL]: return try: self.db.ping(True) # test connection; reconnect upon failure # ... should auto-reconnect; however, it seems to fail the first # time, then work the next time. # Exception (the first time) is: # <class '_mysql_exceptions.OperationalError'>: # (2006, 'MySQL server has gone away') # http://mail.python.org/pipermail/python-list/2008-February/ # 474598.html except mysql.OperationalError: # loss of connection self.db = None self.connect_to_database_mysql( self._database, self._user, self._password, self._server, self._port, self._charset, self._use_unicode)
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L1931-L1949
connect to sql
python
def run(self, sql, autocommit=False, parameters=None): """ Runs a command or a list of commands. Pass a list of sql statements to the sql parameter to get them to execute sequentially :param sql: the sql statement to be executed (str) or a list of sql statements to execute :type sql: str or list :param autocommit: What to set the connection's autocommit setting to before executing the query. :type autocommit: bool :param parameters: The parameters to render the SQL query with. :type parameters: mapping or iterable """ if isinstance(sql, basestring): sql = [sql] with closing(self.get_conn()) as conn: if self.supports_autocommit: self.set_autocommit(conn, autocommit) with closing(conn.cursor()) as cur: for s in sql: if parameters is not None: self.log.info("{} with parameters {}".format(s, parameters)) cur.execute(s, parameters) else: self.log.info(s) cur.execute(s) # If autocommit was set to False for db that supports autocommit, # or if db does not supports autocommit, we do a manual commit. if not self.get_autocommit(conn): conn.commit()
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/hooks/dbapi_hook.py#L132-L166
connect to sql
python
def _connect(self): """Connect to server.""" self._soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._soc.connect((self._ipaddr, self._port)) self._soc.send(_build_request({'cmd': cmd.CMD_MESSAGE_PASSWORD, 'sha': self._password}))
https://github.com/PhracturedBlue/asterisk_mbox/blob/275de1e71ed05c6acff1a5fa87f754f4d385a372/asterisk_mbox/__init__.py#L97-L102
connect to sql
python
def is_disconnect(e, connection, cursor): """ Connection state check from SQLAlchemy: https://bitbucket.org/sqlalchemy/sqlalchemy/src/tip/lib/sqlalchemy/dialects/postgresql/psycopg2.py """ if isinstance(e, OperationalError): # these error messages from libpq: interfaces/libpq/fe-misc.c. # TODO: these are sent through gettext in libpq and we can't # check within other locales - consider using connection.closed return 'terminating connection' in str(e) or \ 'closed the connection' in str(e) or \ 'connection not open' in str(e) or \ 'could not receive data from server' in str(e) elif isinstance(e, InterfaceError): # psycopg2 client errors, psycopg2/conenction.h, psycopg2/cursor.h return 'connection already closed' in str(e) or \ 'cursor already closed' in str(e) elif isinstance(e, ProgrammingError): # not sure where this path is originally from, it may # be obsolete. It really says "losed", not "closed". return "closed the connection unexpectedly" in str(e) else: return False
https://github.com/heroku-python/django-postgrespool/blob/ce83a4d49c19eded86d86d5fcfa8daaeea5ef662/django_postgrespool/base.py#L42-L64
connect to sql
python
def connect(url=None, schema=None, sql_path=None, multiprocessing=False): """Open a new connection to postgres via psycopg2/sqlalchemy """ if url is None: url = os.environ.get("DATABASE_URL") return Database(url, schema, sql_path=sql_path, multiprocessing=multiprocessing)
https://github.com/smnorris/pgdata/blob/8b0294024d5ef30b4ae9184888e2cc7004d1784e/pgdata/__init__.py#L15-L20
connect to sql
python
def connection(self, commit=False): """ Context manager to keep around DB connection. :rtype: sqlite3.Connection SOMEDAY: Get rid of this function. Keeping connection around as an argument to the method using this context manager is probably better as it is more explicit. Also, holding "global state" as instance attribute is bad for supporting threaded search, which is required for more fluent percol integration. """ if commit: self._need_commit = True if self._db: yield self._db else: try: with self._get_db() as db: self._db = db db.create_function("REGEXP", 2, sql_regexp_func) db.create_function("PROGRAM_NAME", 1, sql_program_name_func) db.create_function("PATHDIST", 2, sql_pathdist_func) yield self._db if self._need_commit: db.commit() finally: self._db = None self._need_commit = False
https://github.com/tkf/rash/blob/585da418ec37dd138f1a4277718b6f507e9536a2/rash/database.py#L129-L160
connect to sql
python
def connect_sqs(aws_access_key_id=None, aws_secret_access_key=None, **kwargs): """ :type aws_access_key_id: string :param aws_access_key_id: Your AWS Access Key ID :type aws_secret_access_key: string :param aws_secret_access_key: Your AWS Secret Access Key :rtype: :class:`boto.sqs.connection.SQSConnection` :return: A connection to Amazon's SQS """ from boto.sqs.connection import SQSConnection return SQSConnection(aws_access_key_id, aws_secret_access_key, **kwargs)
https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/boto/__init__.py#L82-L94
connect to sql
python
def set_connection(connection=defaults.sqlalchemy_connection_string_default): """Set the connection string for sqlalchemy and write it to the config file. .. code-block:: python import pyhgnc pyhgnc.set_connection('mysql+pymysql://{user}:{passwd}@{host}/{db}?charset={charset}') .. hint:: valid connection strings - mysql+pymysql://user:passwd@localhost/database?charset=utf8 - postgresql://scott:tiger@localhost/mydatabase - mssql+pyodbc://user:passwd@database - oracle://user:passwd@127.0.0.1:1521/database - Linux: sqlite:////absolute/path/to/database.db - Windows: sqlite:///C:\path\to\database.db :param str connection: sqlalchemy connection string """ config_path = defaults.config_file_path config = RawConfigParser() if not os.path.exists(config_path): with open(config_path, 'w') as config_file: config['database'] = {'sqlalchemy_connection_string': connection} config.write(config_file) log.info('create configuration file {}'.format(config_path)) else: config.read(config_path) config.set('database', 'sqlalchemy_connection_string', connection) with open(config_path, 'w') as configfile: config.write(configfile)
https://github.com/LeKono/pyhgnc/blob/1cae20c40874bfb51581b7c5c1481707e942b5d0/src/pyhgnc/manager/database.py#L423-L464
connect to sql
python
def connect(self): """ Connects to the redis database. """ self._connection = StrictRedis( host=self._host, port=self._port, db=self._database, password=self._password)
https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/signal.py#L47-L53
connect to sql
python
def connect_to_database_odbc_mysql(self, database: str, user: str, password: str, server: str = "localhost", port: int = 3306, driver: str = "{MySQL ODBC 5.1 Driver}", autocommit: bool = True) -> None: """Connects to a MySQL database via ODBC.""" self.connect(engine=ENGINE_MYSQL, interface=INTERFACE_ODBC, database=database, user=user, password=password, host=server, port=port, driver=driver, autocommit=autocommit)
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L1969-L1981
connect to sql
python
async def connect(self): """Create connection pool asynchronously. """ self.pool = await aiomysql.create_pool( loop=self.loop, db=self.database, connect_timeout=self.timeout, **self.connect_params)
https://github.com/05bit/peewee-async/blob/d15f4629da1d9975da4ec37306188e68d288c862/peewee_async.py#L1168-L1175
connect to sql
python
def _executing(self, sql, params=[]): """ Execute and yield rows in a way to support :meth:`close_connection`. """ with self.connection() as connection: for row in connection.execute(sql, params): yield row if not self._db: return
https://github.com/tkf/rash/blob/585da418ec37dd138f1a4277718b6f507e9536a2/rash/database.py#L188-L196
connect to sql
python
def connect_sqs(aws_access_key_id=None, aws_secret_access_key=None, **kwargs): """ :type aws_access_key_id: string :param aws_access_key_id: Your AWS Access Key ID :type aws_secret_access_key: string :param aws_secret_access_key: Your AWS Secret Access Key :rtype: :class:`boto.sqs.connection.SQSConnection` :return: A connection to Amazon's SQS """ from botornado.sqs.connection import AsyncSQSConnection return AsyncSQSConnection(aws_access_key_id, aws_secret_access_key, **kwargs)
https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/botornado/__init__.py#L35-L47
connect to sql
python
def connect(self, config): """Connect to database with given configuration, which may be a dict or a path to a pymatgen-db configuration. """ if isinstance(config, str): conn = dbutil.get_database(config_file=config) elif isinstance(config, dict): conn = dbutil.get_database(settings=config) else: raise ValueError("Configuration, '{}', must be a path to " "a configuration file or dict".format(config)) return conn
https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/builders/core.py#L369-L380
connect to sql
python
def _connect(self): """Connect to our domain""" if not self._db: import boto sdb = boto.connect_sdb() if not self.domain_name: self.domain_name = boto.config.get("DB", "sequence_db", boto.config.get("DB", "db_name", "default")) try: self._db = sdb.get_domain(self.domain_name) except SDBResponseError, e: if e.status == 400: self._db = sdb.create_domain(self.domain_name) else: raise return self._db
https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/boto/sdb/db/sequence.py#L202-L216
connect to sql
python
def connect_mysql(): """ return an inspector object """ MySQLConnection.get_characterset_info = MySQLConnection.get_charset db = create_engine(engine_name) db.echo = True db.connect() return db
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/db/truncate.py#L40-L50
connect to sql
python
def get_connection(connection_details=None): """ Creates a connection to the MySQL DB. """ if connection_details is None: connection_details = get_default_connection_details() return MySQLdb.connect( connection_details['host'], connection_details['user'], connection_details['password'], connection_details['database'] )
https://github.com/evetrivia/thanatos/blob/664c12a8ccf4d27ab0e06e0969bbb6381f74789c/thanatos/database/db_utils.py#L103-L114
connect to sql
python
def _connect(self, servers): """ connect to the given server, e.g.: \\connect localhost:4200 """ self._do_connect(servers.split(' ')) self._verify_connection(verbose=True)
https://github.com/crate/crash/blob/32d3ddc78fd2f7848ed2b99d9cd8889e322528d9/src/crate/crash/command.py#L362-L365
connect to sql
python
def _get_conn(ret=None): ''' Return a MSSQL connection. ''' _options = _get_options(ret) dsn = _options.get('dsn') user = _options.get('user') passwd = _options.get('passwd') return pyodbc.connect('DSN={0};UID={1};PWD={2}'.format( dsn, user, passwd))
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/odbc.py#L169-L181