當前位置: 首頁>>代碼示例>>Python>>正文


Python psycopg2.DatabaseError方法代碼示例

本文整理匯總了Python中psycopg2.DatabaseError方法的典型用法代碼示例。如果您正苦於以下問題:Python psycopg2.DatabaseError方法的具體用法?Python psycopg2.DatabaseError怎麽用?Python psycopg2.DatabaseError使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在psycopg2的用法示例。


在下文中一共展示了psycopg2.DatabaseError方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _nodb_connection

# 需要導入模塊: import psycopg2 [as 別名]
# 或者: from psycopg2 import DatabaseError [as 別名]
def _nodb_connection(self):
        nodb_connection = super(DatabaseWrapper, self)._nodb_connection
        try:
            nodb_connection.ensure_connection()
        except (DatabaseError, WrappedDatabaseError):
            warnings.warn(
                "Normally Django will use a connection to the 'postgres' database "
                "to avoid running initialization queries against the production "
                "database when it's not needed (for example, when running tests). "
                "Django was unable to create a connection to the 'postgres' database "
                "and will use the default database instead.",
                RuntimeWarning
            )
            settings_dict = self.settings_dict.copy()
            settings_dict['NAME'] = settings.DATABASES[DEFAULT_DB_ALIAS]['NAME']
            nodb_connection = self.__class__(
                self.settings_dict.copy(),
                alias=self.alias,
                allow_thread_sharing=False)
        return nodb_connection 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:22,代碼來源:base.py

示例2: _nodb_connection

# 需要導入模塊: import psycopg2 [as 別名]
# 或者: from psycopg2 import DatabaseError [as 別名]
def _nodb_connection(self):
        nodb_connection = super()._nodb_connection
        try:
            nodb_connection.ensure_connection()
        except (Database.DatabaseError, WrappedDatabaseError):
            warnings.warn(
                "Normally Django will use a connection to the 'postgres' database "
                "to avoid running initialization queries against the production "
                "database when it's not needed (for example, when running tests). "
                "Django was unable to create a connection to the 'postgres' database "
                "and will use the default database instead.",
                RuntimeWarning
            )
            settings_dict = self.settings_dict.copy()
            settings_dict['NAME'] = settings.DATABASES[DEFAULT_DB_ALIAS]['NAME']
            nodb_connection = self.__class__(
                self.settings_dict.copy(),
                alias=self.alias,
                allow_thread_sharing=False)
        return nodb_connection 
開發者ID:reBiocoder,項目名稱:bioforum,代碼行數:22,代碼來源:base.py

示例3: create_table

# 需要導入模塊: import psycopg2 [as 別名]
# 或者: from psycopg2 import DatabaseError [as 別名]
def create_table(connect_str_or_path, use_sqlite, command):
    if use_sqlite:
        sqlite_path = connect_str_or_path
        conn = sqlite3.connect(sqlite_path)
        cur = conn.cursor()
        cur.execute(command)
        conn.commit()
        cur.close()
    else:
        conn = None
        try:
            db_connect_str = connect_str_or_path
            conn = psycopg2.connect(db_connect_str)
            cur = conn.cursor()
            cur.execute(command)
            conn.commit()
            cur.close()
        except (Exception, psycopg2.DatabaseError) as error:
            if "already exists" not in str(error):
                print(error)
        finally:
            if conn is not None:
                conn.close() 
開發者ID:MattKleinsmith,項目名稱:pbt,代碼行數:25,代碼來源:utils.py

示例4: load_sqlite_table

# 需要導入模塊: import psycopg2 [as 別名]
# 或者: from psycopg2 import DatabaseError [as 別名]
def load_sqlite_table(database_path, table_name):
    """Returns (table, connection). table is a pandas DataFrame."""
    conn = sqlite3.connect(database_path)
    try:
        df = pd.read_sql("SELECT * FROM %s" % table_name, conn)
        #  print("\nLoading %s table from SQLite3 database." % table_name)
    except DatabaseError as e:
        if 'no such table' in e.args[0]:
            print("\nNo such table: %s" % table_name)
            print("Create the table before loading it. " +
                  "Consider using the create_sqlite_table function")
            raise DatabaseError
        else:
            print(e)
            raise Exception("Failed to create %s table. Unknown error." %
                            table_name)
    return df, conn 
開發者ID:MattKleinsmith,項目名稱:pbt,代碼行數:19,代碼來源:utils.py

示例5: Defect_Dojo_Output

# 需要導入模塊: import psycopg2 [as 別名]
# 或者: from psycopg2 import DatabaseError [as 別名]
def Defect_Dojo_Output(Title, Description):
    DD_Details = Load_Defect_Dojo_Configuration()

    if DD_Details:

        try:
            Impact = 'All Scrummage findings have the potential to cause significant damage to a business\' finances, efficiency and reputation. Therefore, findings should be investigated to assist in reducing this risk.'
            Mitigation = 'It is recommended that this issue be investigated further by the security team to determine whether or not further action needs to be taken.'
            DD_Connection = defectdojo.DefectDojoAPI(DD_Details[1], DD_Details[0], DD_Details[2], debug=False)
            Finding = DD_Connection.create_finding(Title, Description, 'Low', '', str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d')), DD_Details[4], DD_Details[3], DD_Details[5], DD_Details[6], Impact, True, False, Mitigation)

            try:
                Finding = str(int(str(Finding)))
                logging.info(f"{Date()} Connectors Library - DefectDojo finding {Finding} created.")

            except:
                logging.info(f"{Date()} Connectors Library - Failed to create DefectDojo finding.")

        except (Exception, psycopg2.DatabaseError) as Error:
            logging.warning(Date() + str(Error)) 
開發者ID:matamorphosis,項目名稱:Scrummage,代碼行數:22,代碼來源:Connectors.py

示例6: _nodb_connection

# 需要導入模塊: import psycopg2 [as 別名]
# 或者: from psycopg2 import DatabaseError [as 別名]
def _nodb_connection(self):
        nodb_connection = super()._nodb_connection
        try:
            nodb_connection.ensure_connection()
        except (Database.DatabaseError, WrappedDatabaseError):
            warnings.warn(
                "Normally Django will use a connection to the 'postgres' database "
                "to avoid running initialization queries against the production "
                "database when it's not needed (for example, when running tests). "
                "Django was unable to create a connection to the 'postgres' database "
                "and will use the first PostgreSQL database instead.",
                RuntimeWarning
            )
            for connection in connections.all():
                if connection.vendor == 'postgresql' and connection.settings_dict['NAME'] != 'postgres':
                    return self.__class__(
                        {**self.settings_dict, 'NAME': connection.settings_dict['NAME']},
                        alias=self.alias,
                        allow_thread_sharing=False,
                    )
        return nodb_connection 
開發者ID:PacktPublishing,項目名稱:Hands-On-Application-Development-with-PyCharm,代碼行數:23,代碼來源:base.py

示例7: _nodb_connection

# 需要導入模塊: import psycopg2 [as 別名]
# 或者: from psycopg2 import DatabaseError [as 別名]
def _nodb_connection(self):
        nodb_connection = super(DatabaseWrapper, self)._nodb_connection
        try:
            nodb_connection.ensure_connection()
        except (Database.DatabaseError, WrappedDatabaseError):
            warnings.warn(
                "Normally Django will use a connection to the 'postgres' database "
                "to avoid running initialization queries against the production "
                "database when it's not needed (for example, when running tests). "
                "Django was unable to create a connection to the 'postgres' database "
                "and will use the default database instead.",
                RuntimeWarning
            )
            settings_dict = self.settings_dict.copy()
            settings_dict['NAME'] = settings.DATABASES[DEFAULT_DB_ALIAS]['NAME']
            nodb_connection = self.__class__(
                self.settings_dict.copy(),
                alias=self.alias,
                allow_thread_sharing=False)
        return nodb_connection 
開發者ID:Yeah-Kun,項目名稱:python,代碼行數:22,代碼來源:base.py

示例8: _create_instrument_day_data_table

# 需要導入模塊: import psycopg2 [as 別名]
# 或者: from psycopg2 import DatabaseError [as 別名]
def _create_instrument_day_data_table(self, _instrument):
        try:
            self.instrument_day_data_cur.execute(
                "CREATE TABLE {}"
                "("
                "TradingDay char(8) PRIMARY KEY,"
                "OpenPrice double precision,"
                "HighPrice double precision,"
                "LowPrice double precision,"
                "ClosePrice double precision,"
                "SettlementPrice double precision,"
                "Volume integer,"
                "OpenInterest double precision,"
                "PreSettlementPrice double precision"
                ")".format(_instrument))
            self.instrument_day_data_con.commit()
        except psycopg2.DatabaseError as e:
            logging.error(e)
            self.instrument_day_data_con.rollback()
            sys.exit(1) 
開發者ID:ppaanngggg,項目名稱:ParadoxTrading,代碼行數:22,代碼來源:StoreDailyData.py

示例9: _create_product_index_table

# 需要導入模塊: import psycopg2 [as 別名]
# 或者: from psycopg2 import DatabaseError [as 別名]
def _create_product_index_table(self, _product):
        try:
            self.product_index_cur.execute(
                "CREATE TABLE {}"
                "("
                "TradingDay char(8) PRIMARY KEY,"
                "OpenPrice double precision,"
                "HighPrice double precision,"
                "LowPrice double precision,"
                "ClosePrice double precision,"
                "Volume integer,"
                "OpenInterest double precision"
                ")".format(_product))
            self.product_index_con.commit()
        except psycopg2.DatabaseError as e:
            logging.error(e)
            self.product_index_con.rollback()
            sys.exit(1) 
開發者ID:ppaanngggg,項目名稱:ParadoxTrading,代碼行數:20,代碼來源:StoreDailyData.py

示例10: _create_dominant_index_table

# 需要導入模塊: import psycopg2 [as 別名]
# 或者: from psycopg2 import DatabaseError [as 別名]
def _create_dominant_index_table(self, _product):
        try:
            self.dominant_index_cur.execute(
                "CREATE TABLE {}"
                "("
                "TradingDay char(8) PRIMARY KEY,"
                "OpenPrice double precision,"
                "HighPrice double precision,"
                "LowPrice double precision,"
                "ClosePrice double precision,"
                "Volume integer,"
                "OpenInterest double precision"
                ")".format(_product))
            self.dominant_index_con.commit()
        except psycopg2.DatabaseError as e:
            logging.error(e)
            self.dominant_index_con.rollback()
            sys.exit(1) 
開發者ID:ppaanngggg,項目名稱:ParadoxTrading,代碼行數:20,代碼來源:StoreDailyData.py

示例11: create_physical_repslot

# 需要導入模塊: import psycopg2 [as 別名]
# 或者: from psycopg2 import DatabaseError [as 別名]
def create_physical_repslot(self, slot_name):
        """
        Create a physical replication slot using the streaming connection
        :param str slot_name: Replication slot name
        """
        cursor = self._cursor()
        try:
            # In the following query, the slot name is directly passed
            # to the CREATE_REPLICATION_SLOT command, without any
            # quoting. This is a characteristic of the streaming
            # connection, otherwise if will fail with a generic
            # "syntax error"
            cursor.execute('CREATE_REPLICATION_SLOT %s PHYSICAL' % slot_name)
            _logger.info("Replication slot '%s' successfully created",
                         slot_name)
        except psycopg2.DatabaseError as exc:
            if exc.pgcode == DUPLICATE_OBJECT:
                # A replication slot with the same name exists
                raise PostgresDuplicateReplicationSlot()
            elif exc.pgcode == CONFIGURATION_LIMIT_EXCEEDED:
                # Unable to create a new physical replication slot.
                # All slots are full.
                raise PostgresReplicationSlotsFull()
            else:
                raise PostgresException(force_str(exc).strip()) 
開發者ID:2ndquadrant-it,項目名稱:barman,代碼行數:27,代碼來源:postgres.py

示例12: drop_repslot

# 需要導入模塊: import psycopg2 [as 別名]
# 或者: from psycopg2 import DatabaseError [as 別名]
def drop_repslot(self, slot_name):
        """
        Drop a physical replication slot using the streaming connection
        :param str slot_name: Replication slot name
        """
        cursor = self._cursor()
        try:
            # In the following query, the slot name is directly passed
            # to the DROP_REPLICATION_SLOT command, without any
            # quoting. This is a characteristic of the streaming
            # connection, otherwise if will fail with a generic
            # "syntax error"
            cursor.execute('DROP_REPLICATION_SLOT %s' % slot_name)
            _logger.info("Replication slot '%s' successfully dropped",
                         slot_name)
        except psycopg2.DatabaseError as exc:
            if exc.pgcode == UNDEFINED_OBJECT:
                # A replication slot with the that name does not exist
                raise PostgresInvalidReplicationSlot()
            if exc.pgcode == OBJECT_IN_USE:
                # The replication slot is still in use
                raise PostgresReplicationSlotInUse()
            else:
                raise PostgresException(force_str(exc).strip()) 
開發者ID:2ndquadrant-it,項目名稱:barman,代碼行數:26,代碼來源:postgres.py

示例13: setUp

# 需要導入模塊: import psycopg2 [as 別名]
# 或者: from psycopg2 import DatabaseError [as 別名]
def setUp(self):
        ConnectingTestCase.setUp(self)

        curs = self.conn.cursor()
        # Drop table if it already exists
        try:
            curs.execute("DROP TABLE table1")
            self.conn.commit()
        except psycopg2.DatabaseError:
            self.conn.rollback()
        try:
            curs.execute("DROP TABLE table2")
            self.conn.commit()
        except psycopg2.DatabaseError:
            self.conn.rollback()
        # Create sample data
        curs.execute("""
            CREATE TABLE table1 (
                id int PRIMARY KEY,
                name text)
        """)
        curs.execute("INSERT INTO table1 VALUES (1, 'hello')")
        curs.execute("CREATE TABLE table2 (id int PRIMARY KEY)")
        self.conn.commit() 
開發者ID:synthetichealth,項目名稱:syntheticmass,代碼行數:26,代碼來源:test_transaction.py

示例14: test_deadlock

# 需要導入模塊: import psycopg2 [as 別名]
# 或者: from psycopg2 import DatabaseError [as 別名]
def test_deadlock(self):
        self.thread1_error = self.thread2_error = None
        step1 = threading.Event()
        step2 = threading.Event()

        def task1():
            try:
                conn = self.connect()
                curs = conn.cursor()
                curs.execute("LOCK table1 IN ACCESS EXCLUSIVE MODE")
                step1.set()
                step2.wait()
                curs.execute("LOCK table2 IN ACCESS EXCLUSIVE MODE")
            except psycopg2.DatabaseError, exc:
                self.thread1_error = exc
                step1.set()
            conn.close() 
開發者ID:synthetichealth,項目名稱:syntheticmass,代碼行數:19,代碼來源:test_transaction.py

示例15: test_serialisation_failure

# 需要導入模塊: import psycopg2 [as 別名]
# 或者: from psycopg2 import DatabaseError [as 別名]
def test_serialisation_failure(self):
        self.thread1_error = self.thread2_error = None
        step1 = threading.Event()
        step2 = threading.Event()

        def task1():
            try:
                conn = self.connect()
                curs = conn.cursor()
                curs.execute("SELECT name FROM table1 WHERE id = 1")
                curs.fetchall()
                step1.set()
                step2.wait()
                curs.execute("UPDATE table1 SET name='task1' WHERE id = 1")
                conn.commit()
            except psycopg2.DatabaseError, exc:
                self.thread1_error = exc
                step1.set()
            conn.close() 
開發者ID:synthetichealth,項目名稱:syntheticmass,代碼行數:21,代碼來源:test_transaction.py


注:本文中的psycopg2.DatabaseError方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。