当前位置: 首页>>代码示例>>Python>>正文


Python psycopg2.connect方法代码示例

本文整理汇总了Python中psycopg2.connect方法的典型用法代码示例。如果您正苦于以下问题:Python psycopg2.connect方法的具体用法?Python psycopg2.connect怎么用?Python psycopg2.connect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在psycopg2的用法示例。


在下文中一共展示了psycopg2.connect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_copy_data_from

# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import connect [as 别名]
def test_copy_data_from(self):
        try:
            tmpdir = tempfile.mkdtemp()

            # create new database
            with testing.postgresql.Postgresql(base_dir=tmpdir) as pgsql:
                conn = pg8000.connect(**pgsql.dsn())
                with closing(conn.cursor()) as cursor:
                    cursor.execute("CREATE TABLE hello(id int, value varchar(256))")
                    cursor.execute("INSERT INTO hello values(1, 'hello'), (2, 'ciao')")
                conn.commit()
                conn.close()

            # create another database from first one
            data_dir = os.path.join(tmpdir, 'data')
            with testing.postgresql.Postgresql(copy_data_from=data_dir) as pgsql:
                conn = pg8000.connect(**pgsql.dsn())
                with closing(conn.cursor()) as cursor:
                    cursor.execute('SELECT * FROM hello ORDER BY id')
                    self.assertEqual(cursor.fetchall(), ([1, 'hello'], [2, 'ciao']))
                conn.close()
        finally:
            rmtree(tmpdir) 
开发者ID:tk0miya,项目名称:testing.postgresql,代码行数:25,代码来源:test_postgresql.py

示例2: test_PostgresqlFactory_with_initialized_handler

# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import connect [as 别名]
def test_PostgresqlFactory_with_initialized_handler(self):
        def handler(pgsql):
            conn = pg8000.connect(**pgsql.dsn())
            with closing(conn.cursor()) as cursor:
                cursor.execute("CREATE TABLE hello(id int, value varchar(256))")
                cursor.execute("INSERT INTO hello values(1, 'hello'), (2, 'ciao')")
            conn.commit()
            conn.close()

        Postgresql = testing.postgresql.PostgresqlFactory(cache_initialized_db=True,
                                                          on_initialized=handler)
        try:
            with Postgresql() as pgsql:
                conn = pg8000.connect(**pgsql.dsn())
                with closing(conn.cursor()) as cursor:
                    cursor.execute('SELECT * FROM hello ORDER BY id')
                    self.assertEqual(cursor.fetchall(), ([1, 'hello'], [2, 'ciao']))
                conn.close()
        finally:
            Postgresql.clear_cache() 
开发者ID:tk0miya,项目名称:testing.postgresql,代码行数:22,代码来源:test_postgresql.py

示例3: process

# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import connect [as 别名]
def process(iid, infile):
    dbh = psycopg2.connect(database="firmware", user="firmadyne",
                           password="firmadyne", host="127.0.0.1")
    cur = dbh.cursor()

    (files, links) = getFileHashes(infile)

    oids = getOids(files, cur)

    fdict = dict([(h, (filename, uid, gid, mode, mime, score)) \
            for (filename, h, uid, gid, mode, mime, score) in files])

    file2oid = [(fdict[h], oid) for (h, oid) in oids.items()]

    insertObjectToImage(iid, file2oid, links, cur)

    dbh.commit()

    dbh.close() 
开发者ID:kyechou,项目名称:firmanal,代码行数:21,代码来源:importdb.py

示例4: insert_ip

# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import connect [as 别名]
def insert_ip (iid, ip):
    import psycopg2
    db = psycopg2.connect (dbname = "firmware",
                           user = "firmadyne",
                           password = "firmadyne",
                           host = "127.0.0.1")
    try:
        cur = db.cursor()
        cur.execute("UPDATE image SET ip='" + ip + "' WHERE id=" + iid)
        db.commit()
    except BaseException:
        ret = False
        traceback.print_exc()
        db.rollback()
    finally:
        if cur:
            cur.close() 
开发者ID:kyechou,项目名称:firmanal,代码行数:19,代码来源:makeNetwork.py

示例5: __init__

# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import connect [as 别名]
def __init__(self, database, relation, port=None):
        """Postgres estimator (i.e., EXPLAIN).  Must have the PG server live.
        E.g.,
            def MakeEstimators():
                return [Postgres('dmv', 'vehicle_reg', None), ...]
        Args:
          database: string, the database name.
          relation: string, the relation name.
          port: int, the port.
        """
        import psycopg2

        super(Postgres, self).__init__()

        self.conn = psycopg2.connect(database=database, port=port)
        self.conn.autocommit = True
        self.cursor = self.conn.cursor()

        self.cursor.execute('analyze ' + relation + ';')
        self.conn.commit()

        self.database = database
        self.relation = relation 
开发者ID:naru-project,项目名称:naru,代码行数:25,代码来源:estimators.py

示例6: __init__

# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import connect [as 别名]
def __init__(
        self,
        database=None,
        user=None,
        password=None,
        host=None,
        port=None,
        dsn=None,
        **kwargs,
    ):
        self._conn_params = {}
        self.conn = None
        self.dbname = None
        self.user = None
        self.password = None
        self.host = None
        self.port = None
        self.server_version = None
        self.extra_args = None
        self.connect(database, user, password, host, port, dsn, **kwargs)
        self.reset_expanded = None 
开发者ID:dbcli,项目名称:pgcli,代码行数:23,代码来源:pgexecute.py

示例7: pg_connection

# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import connect [as 别名]
def pg_connection(self):
        """
        Return a connection to the db.
        """
        dbname = self.server_opts['db_name']
        user = self.server_opts['db_user']
        host = self.server_opts['db_host']
        password = self.server_opts['db_password']
        message = ''
        try:
            pg_conn = connect("dbname='%s' user='%s' host='%s' password='%s'"\
                % (dbname, user, host, password))
        except OperationalError:
            return None, 'Error : Server cannot connect to database'
        try:
            pg_conn.cursor().execute("""SELECT * FROM USERS""")
        except ProgrammingError:
            return None, 'Error : Server cannot connect to table in database'
        return pg_conn, message 
开发者ID:nbeguier,项目名称:cassh,代码行数:21,代码来源:tools.py

示例8: init_pg

# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import connect [as 别名]
def init_pg(pg_conn):
    """
    Initialize pg database
    """
    if pg_conn is None:
        print('I am unable to connect to the database')
        sys.exit(1)
    cur = pg_conn.cursor()

    sql_files = [f for f in listdir(SQL_SERVER_PATH) if isfile(join(SQL_SERVER_PATH, f))]

    for sql_file in sql_files:
        with open('%s/%s' % (SQL_SERVER_PATH, sql_file), 'r') as sql_model_file:
            cur.execute(sql_model_file.read())
            pg_conn.commit()

    cur.close()
    pg_conn.close() 
开发者ID:nbeguier,项目名称:cassh,代码行数:20,代码来源:init_pg.py

示例9: clean_pg

# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import connect [as 别名]
def clean_pg(pg_conn):
    """
    Clean pg database
    """
    if pg_conn is None:
        print('I am unable to connect to the database')
        sys.exit(1)
    cur = pg_conn.cursor()

    cur.execute(
        """
        DELETE FROM USERS
        """)
    cur.execute(
        """
        DELETE FROM REVOCATION
        """)
    pg_conn.commit()

    cur.close()
    pg_conn.close() 
开发者ID:nbeguier,项目名称:cassh,代码行数:23,代码来源:clean_pg.py

示例10: _connect

# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import connect [as 别名]
def _connect(self, key=None):
        """Create a new connection and assign it to 'key' if not None."""
        if self._dsn:
            conn = psycopg2.connect(self._dsn)
        else:
            conn = psycopg2.connect(**self._db_config)

        if not self._disable_pooling:
            if key is not None:
                self._used[key] = conn
                self._rused[id(conn)] = key
                self._tused[id(conn)] = time.time()
            else:
                self._pool.append(conn)

        self._log('Connection created %s' % conn)
        return conn 
开发者ID:masroore,项目名称:pg_simple,代码行数:19,代码来源:pool.py

示例11: licensefossology

# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import connect [as 别名]
def licensefossology((packages)):
	## Also run FOSSology. This requires that the user has enough privileges to actually connect to the
	## FOSSology database, for example by being in the correct group.
	fossologyres = []
	fossscanfiles = map(lambda x: os.path.join(x[2], x[3]), packages)
	scanargs = ["/usr/share/fossology/nomos/agent/nomossa"] + fossscanfiles
	p2 = subprocess.Popen(scanargs, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
	(stanout, stanerr) = p2.communicate()
	if "FATAL" in stanout:
		## TODO: better error handling
		return None
	else:
		fosslines = stanout.strip().split("\n")
		for j in range(0,len(fosslines)):
			fossysplit = fosslines[j].strip().rsplit(" ", 1)
			licenses = fossysplit[-1].split(',')
			fossologyres.append((packages[j][5], set(licenses)))
	return fossologyres

## TODO: get rid of ninkaversion before we call this method
## TODO: process more files at once to reduce overhead of calling ctags 
开发者ID:armijnhemel,项目名称:binaryanalysis,代码行数:23,代码来源:createdb.py

示例12: create_tables

# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import connect [as 别名]
def create_tables(self, request):
        self.conn = pymysql.connect(host="127.0.0.1",
                                    user="piiuser",
                                    password="p11secret",
                                    database="piidb"
                                    )

        with self.conn.cursor() as cursor:
            self.execute_script(cursor, char_data_types)
            cursor.execute("commit")
            cursor.close()

        def drop_tables():
            with self.conn.cursor() as drop_cursor:
                self.execute_script(drop_cursor, self.char_db_drop)
                logging.info("Executed drop script")
                drop_cursor.close()
            self.conn.close()

        request.addfinalizer(drop_tables) 
开发者ID:tokern,项目名称:piicatcher,代码行数:22,代码来源:test_databases.py

示例13: _connect

# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import connect [as 别名]
def _connect(self):
        if self.application_name is None:
            st = inspect.stack()
            self.application_name = os.path.basename(st[-1][1])
        conn_args = dict(
            host=self.url.hostname,
            port=self.url.port,
            database=self.url.database,
            user=self.url.username,
            password=self.url.password,
            application_name=self.application_name + "/" + hgvs.__version__,
        )
        if self.pooling:
            _logger.info("Using UTA ThreadedConnectionPool")
            self._pool = psycopg2.pool.ThreadedConnectionPool(
                hgvs.global_config.uta.pool_min, hgvs.global_config.uta.pool_max, **conn_args)
        else:
            self._conn = psycopg2.connect(**conn_args)
            self._conn.autocommit = True

        self._ensure_schema_exists()

        # remap sqlite's ? placeholders to psycopg2's %s
        self._queries = {k: v.replace('?', '%s') for k, v in six.iteritems(self._queries)} 
开发者ID:biocommons,项目名称:hgvs,代码行数:26,代码来源:ncbi.py

示例14: get_connection_params

# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import connect [as 别名]
def get_connection_params(self):
        settings_dict = self.settings_dict
        # None may be used to connect to the default 'postgres' db
        if settings_dict['NAME'] == '':
            from django.core.exceptions import ImproperlyConfigured
            raise ImproperlyConfigured(
                "settings.DATABASES is improperly configured. "
                "Please supply the NAME value.")
        conn_params = {
            'database': settings_dict['NAME'] or 'postgres',
        }
        conn_params.update(settings_dict['OPTIONS'])
        conn_params.pop('isolation_level', None)
        if settings_dict['USER']:
            conn_params['user'] = settings_dict['USER']
        if settings_dict['PASSWORD']:
            conn_params['password'] = force_str(settings_dict['PASSWORD'])
        if settings_dict['HOST']:
            conn_params['host'] = settings_dict['HOST']
        if settings_dict['PORT']:
            conn_params['port'] = settings_dict['PORT']
        return conn_params 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:24,代码来源:base.py

示例15: get_new_connection

# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import connect [as 别名]
def get_new_connection(self, conn_params):
        connection = Database.connect(**conn_params)

        # self.isolation_level must be set:
        # - after connecting to the database in order to obtain the database's
        #   default when no value is explicitly specified in options.
        # - before calling _set_autocommit() because if autocommit is on, that
        #   will set connection.isolation_level to ISOLATION_LEVEL_AUTOCOMMIT.
        options = self.settings_dict['OPTIONS']
        try:
            self.isolation_level = options['isolation_level']
        except KeyError:
            self.isolation_level = connection.isolation_level
        else:
            # Set the isolation level to the value from OPTIONS.
            if self.isolation_level != connection.isolation_level:
                connection.set_session(isolation_level=self.isolation_level)

        return connection 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:21,代码来源:base.py


注:本文中的psycopg2.connect方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。