本文整理汇总了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
示例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
示例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()
示例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
示例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))
示例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
示例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
示例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)
示例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)
示例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)
示例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())
示例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())
示例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()
示例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()
示例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()