本文整理汇总了Python中psycopg2.Error方法的典型用法代码示例。如果您正苦于以下问题:Python psycopg2.Error方法的具体用法?Python psycopg2.Error怎么用?Python psycopg2.Error使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类psycopg2
的用法示例。
在下文中一共展示了psycopg2.Error方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create_user
# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import Error [as 别名]
def create_user(conn, username, password):
try:
cur = conn.cursor()
cur.execute("SELECT passwd FROM pg_shadow WHERE usename = %s", [username])
row = cur.fetchone()
if row:
m = hashlib.md5()
m.update(password + username)
encrypted_password = "md5" + m.hexdigest()
if encrypted_password != row[0]:
cur.execute("ALTER USER " + username + " ENCRYPTED PASSWORD %s SUPERUSER REPLICATION", [password])
else:
cur.execute("CREATE USER " + username + " WITH ENCRYPTED PASSWORD %s SUPERUSER REPLICATION", [password])
conn.commit()
return True
except psycopg2.Error as e:
print(e)
conn.rollback()
return False
示例2: stop_subscription
# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import Error [as 别名]
def stop_subscription(db):
"""Stop subscription in given database. Return True if success"""
db_conn = connect('Destination', db_name=db)
db_conn.autocommit = True
cur = db_conn.cursor()
try:
while True:
cur.execute(
"SELECT * FROM pglogical.drop_subscription(subscription_name := %s, ifexists := true)",
['subscription']
)
if cur.fetchone()[0] == 0:
break
sleep(1)
except Error:
return False
return True
示例3: start_subscription
# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import Error [as 别名]
def start_subscription(db):
db_conn = connect('Destination', db)
db_conn.autocommit = True
try:
c = db_conn.cursor()
c.execute(
"""
SELECT pglogical.create_subscription(
subscription_name := 'subscription',
synchronize_structure := false,
synchronize_data := true,
provider_dsn := %s
);
""",
[get_dsn_for_pglogical('Source', db)]
)
return True
except Error:
return False
示例4: store_setup_result
# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import Error [as 别名]
def store_setup_result(target, db, result):
db_conn = connect(target, db)
if not db_conn:
return False
try:
c = db_conn.cursor()
c.execute("CREATE TABLE IF NOT EXISTS pglogical.pgrepup_setup(result BOOL NOT NULL PRIMARY KEY)")
c.execute("TRUNCATE pglogical.pgrepup_setup")
c.execute("INSERT INTO pglogical.pgrepup_setup VALUES (%s)", [result])
db_conn.commit()
except Error:
db_conn.rollback()
return False
return True
示例5: get_pg_hba_contents
# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import Error [as 别名]
def get_pg_hba_contents(conn):
pg_hba_path = get_setting_value(conn, "hba_file")
if not pg_hba_path:
return None
try:
temp_table = "pghba_" + uuid.uuid4().hex
cur = conn.cursor()
cur.execute("CREATE TEMP TABLE " + temp_table + " (content text)")
cur.execute("COPY " + temp_table + " FROM %s", [pg_hba_path])
cur.execute("SELECT * FROM " + temp_table + ";")
rows = cur.fetchall()
conn.rollback()
return rows
except psycopg2.Error as e:
print(e)
return None
示例6: filler_run_shim
# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import Error [as 别名]
def filler_run_shim(self, mode):
try:
self.queue_filler_proc(mode)
except KeyboardInterrupt:
print("Saw keyboard interrupt. Breaking!")
return
except Exception:
print("Error!")
print("Error!")
print("Error!")
print("Error!")
traceback.print_exc()
with open("error %s - %s.txt" % ("rawjobdispatcher", time.time()), "w") as fp:
fp.write("Manager crashed?\n")
fp.write(traceback.format_exc())
raise
示例7: get_status
# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import Error [as 别名]
def get_status(self):
if any([tmp.is_alive() for tmp in self.fetch_procs.values()]):
with self.count_lock:
return "Worker: %s, alive: %s, control: %s, last_rx: %s, active_jobs: %s, jobs_out: %s, jobs_in: %s." % (
[tmp.ident for tmp in self.fetch_procs.values()],
[tmp.is_alive() for tmp in self.fetch_procs.values()],
self.run_flag.value,
self.last_rx,
self.active_jobs,
self.jobs_out,
self.jobs_in,
)
return "Worker is none! Error!"
示例8: run_shim
# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import Error [as 别名]
def run_shim(cls, job_queue, run_flag, test_mode):
try:
instance = cls(job_queue, run_flag, test_mode=test_mode)
instance.run()
except KeyboardInterrupt:
print("Saw keyboard interrupt. Breaking!")
run_flag.value = 0
except Exception:
print("Error!")
print("Error!")
print("Error!")
print("Error!")
traceback.print_exc()
with open("error %s - %s.txt" % ("multijobmanager", time.time()), "w") as fp:
fp.write("Manager crashed?\n")
fp.write(traceback.format_exc())
raise
示例9: populate_cache
# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import Error [as 别名]
def populate_cache(conn):
try:
cursor = conn.cursor()
cursor.execute("SELECT * FROM measurement_types")
for row in cursor.fetchall():
measurements_dict[row[1]] = [row[0], row[2]]
cursor.execute("SELECT * FROM locations")
for row in cursor.fetchall():
locations_dict[row[1]+' '+row[3]] = row[0]
cursor.close()
except (Exception, psycopg2.Error) as error:
print("Error thrown while trying to populate cache")
print(error)
print("Finished populating cache")
# Iterate through paginated API responses
示例10: moveTableToSchema
# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import Error [as 别名]
def moveTableToSchema(table, schemaName, dbConnectionParam):
try:
with pg.connect(dbConnectionParam) as conn:
with conn.cursor() as cur:
# create the schema
cur.execute('CREATE SCHEMA IF NOT EXISTS ' + schemaName + ';')
conn.commit()
# move the table to the right schema
cur.execute('ALTER TABLE ' + table + ' SET SCHEMA ' + schemaName + ';')
conn.commit()
except pg.Error as e:
six.print_("Error in dealing with the database.", file=sys.stderr)
six.print_("pg.Error ({0}): {1}".format(e.pgcode, e.pgerror), file=sys.stderr)
six.print_(str(e), file=sys.stderr)
except pg.Warning as w:
six.print_("Warning from the database.", file=sys.stderr)
six.print_("pg.Warning: {0}".format(str(w)), file=sys.stderr)
#############################################################
示例11: connect_to_master
# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import Error [as 别名]
def connect_to_master():
citus_host = environ.get('CITUS_HOST', 'master')
postgres_pass = environ.get('POSTGRES_PASSWORD', '')
postgres_user = environ.get('POSTGRES_USER', 'postgres')
postgres_db = environ.get('POSTGRES_DB', postgres_user)
conn = None
while conn is None:
try:
conn = psycopg2.connect("dbname=%s user=%s host=%s password=%s" %
(postgres_db, postgres_user, citus_host, postgres_pass))
except psycopg2.OperationalError as error:
print("Could not connect to %s, trying again in 1 second" % citus_host)
sleep(1)
except (Exception, psycopg2.Error) as error:
raise error
conn.autocommit = True
print("connected to %s" % citus_host, file=stderr)
return conn
# main logic loop for the manager
示例12: close
# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import Error [as 别名]
def close(self):
self.validate_thread_sharing()
if self.connection is None:
return
try:
self.connection.close()
self.connection = None
except Database.Error:
# In some cases (database restart, network connection lost etc...)
# the connection to the database is lost without giving Django a
# notification. If we don't set self.connection to None, the error
# will occur a every request.
self.connection = None
logger.warning('psycopg2 error while closing the connection.',
exc_info=sys.exc_info()
)
raise
示例13: server_txt_version
# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import Error [as 别名]
def server_txt_version(self):
"""
Human readable version of PostgreSQL (calculated from server_version)
:rtype: str|None
"""
try:
conn = self.connect()
major = int(conn.server_version / 10000)
minor = int(conn.server_version / 100 % 100)
patch = int(conn.server_version % 100)
if major < 10:
return "%d.%d.%d" % (major, minor, patch)
if minor != 0:
_logger.warning(
"Unexpected non zero minor version %s in %s",
minor, conn.server_version)
return "%d.%d" % (major, patch)
except PostgresConnectionError as e:
_logger.debug("Error retrieving PostgreSQL version: %s",
force_str(e).strip())
return None
示例14: has_pgespresso
# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import Error [as 别名]
def has_pgespresso(self):
"""
Returns true if the `pgespresso` extension is available
"""
try:
# pg_extension is only available from Postgres 9.1+
if self.server_version < 90100:
return False
cur = self._cursor()
cur.execute("SELECT count(*) FROM pg_extension "
"WHERE extname = 'pgespresso'")
q_result = cur.fetchone()[0]
return q_result > 0
except (PostgresConnectionError, psycopg2.Error) as e:
_logger.debug("Error retrieving pgespresso information: %s",
force_str(e).strip())
return None
示例15: current_size
# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import Error [as 别名]
def current_size(self):
"""
Returns the total size of the PostgreSQL server
(requires superuser or pg_read_all_stats)
"""
if not self.has_backup_privileges:
return None
try:
cur = self._cursor()
cur.execute(
"SELECT sum(pg_tablespace_size(oid)) "
"FROM pg_tablespace")
return cur.fetchone()[0]
except (PostgresConnectionError, psycopg2.Error) as e:
_logger.debug("Error retrieving PostgreSQL total size: %s",
force_str(e).strip())
return None