def execute(self, sql):
try:
cursor = self.db.cursor()
cursor.execute(sql)
self.db.commit()
except (AttributeError, MySQLdb.OperationalError):
self.connect()
cursor = self.db.cursor()
cursor.execute(sql)
self.db.commit()
return cursor
python类OperationalError()的实例源码
def execute(self, query, args=None):
try:
# args is None means no string interpolation
return self.cursor.execute(query, args)
except Database.OperationalError as e:
# Map some error codes to IntegrityError, since they seem to be
# misclassified and Django would prefer the more logical place.
if e.args[0] in self.codes_for_integrityerror:
six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
raise
def executemany(self, query, args):
try:
return self.cursor.executemany(query, args)
except Database.OperationalError as e:
# Map some error codes to IntegrityError, since they seem to be
# misclassified and Django would prefer the more logical place.
if e.args[0] in self.codes_for_integrityerror:
six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
raise
def _test_db_conn(self):
import MySQLdb
try:
MySQLdb.connect(host=self.db_host, port=int(self.db_port),
user=self.db_user, passwd=self.db_pass, db=self.db)
color_print('???????', 'green')
return True
except MySQLdb.OperationalError, e:
color_print('??????? %s' % e, 'red')
return False
def execute(self, query, args=None):
try:
# args is None means no string interpolation
return self.cursor.execute(query, args)
except Database.OperationalError as e:
# Map some error codes to IntegrityError, since they seem to be
# misclassified and Django would prefer the more logical place.
if e.args[0] in self.codes_for_integrityerror:
six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
raise
def executemany(self, query, args):
try:
return self.cursor.executemany(query, args)
except Database.OperationalError as e:
# Map some error codes to IntegrityError, since they seem to be
# misclassified and Django would prefer the more logical place.
if e.args[0] in self.codes_for_integrityerror:
six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
raise
def execute(self, query, args=None):
try:
# args is None means no string interpolation
return self.cursor.execute(query, args)
except Database.OperationalError as e:
# Map some error codes to IntegrityError, since they seem to be
# misclassified and Django would prefer the more logical place.
if e.args[0] in self.codes_for_integrityerror:
six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
raise
def executemany(self, query, args):
try:
return self.cursor.executemany(query, args)
except Database.OperationalError as e:
# Map some error codes to IntegrityError, since they seem to be
# misclassified and Django would prefer the more logical place.
if e.args[0] in self.codes_for_integrityerror:
six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
raise
connection_pool.py 文件源码
项目:python_for_linux_system_administration
作者: lalor
项目源码
文件源码
阅读 44
收藏 0
点赞 0
评论 0
def exec_sql(self, sql):
conn = self._get_conn()
try:
with conn as cur:
cur.execute(sql)
return cur.fetchall()
except MySQLdb.ProgrammingError as e:
LOG.error("execute sql ({0}) error {1}".format(sql, e))
raise e
except MySQLdb.OperationalError as e:
# create connection if connection has interrupted
conn = self._create_new_conn()
raise e
finally:
self._put_conn(conn)
def query(self, sql):
try:
cursor = self.conn.cursor()
cursor.execute(sql)
except (AttributeError, mdb.OperationalError):
self.connect()
cursor = self.conn.cursor()
cursor.execute(sql)
return cursor
def execute(self, query, args=None):
try:
# args is None means no string interpolation
return self.cursor.execute(query, args)
except Database.OperationalError as e:
# Map some error codes to IntegrityError, since they seem to be
# misclassified and Django would prefer the more logical place.
if e.args[0] in self.codes_for_integrityerror:
six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
raise
def executemany(self, query, args):
try:
return self.cursor.executemany(query, args)
except Database.OperationalError as e:
# Map some error codes to IntegrityError, since they seem to be
# misclassified and Django would prefer the more logical place.
if e.args[0] in self.codes_for_integrityerror:
six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
raise
def exec_sql(self, sql):
conn = self._get_conn()
try:
with conn as cur:
cur.execute(sql)
return cur.fetchall()
except MySQLdb.ProgrammingError as e:
LOG.error("execute sql ({0}) error {1}".format(sql, e))
raise e
except MySQLdb.OperationalError as e:
# create connection if connection has interrupted
conn = self._create_new_conn()
raise e
finally:
self._put_conn(conn)
def grant_exists(self, db_name, db_user, remote_ip):
cursor = self.connection.cursor()
priv_string = "GRANT ALL PRIVILEGES ON `{}`.* " \
"TO '{}'@'{}'".format(db_name, db_user, remote_ip)
try:
cursor.execute("SHOW GRANTS for '{}'@'{}'".format(db_user,
remote_ip))
grants = [i[0] for i in cursor.fetchall()]
except MySQLdb.OperationalError:
return False
finally:
cursor.close()
# TODO: review for different grants
return priv_string in grants
def grant_exists(self, db_name, db_user, remote_ip):
cursor = self.connection.cursor()
priv_string = "GRANT ALL PRIVILEGES ON `{}`.* " \
"TO '{}'@'{}'".format(db_name, db_user, remote_ip)
try:
cursor.execute("SHOW GRANTS for '{}'@'{}'".format(db_user,
remote_ip))
grants = [i[0] for i in cursor.fetchall()]
except MySQLdb.OperationalError:
return False
finally:
cursor.close()
# TODO: review for different grants
return priv_string in grants
def run_conn_fun(fun,*args):
try:
global conn
result=yield getattr(conn,fun)(*args)
except (MySQLdb.OperationalError,adbapi.ConnectionLost):
try:
conn.close()
except:
pass
conn=adbapi.ConnectionPool("MySQLdb",host=MYSQLCONFIG["host"],user=MYSQLCONFIG["user"],passwd=MYSQLCONFIG["passwd"],charset=MYSQLCONFIG["charset"],port=MYSQLCONFIG["port"],db=MYSQLCONFIG["db"],cp_reconnect=True)
result=yield getattr(conn,fun)(*args)
defer.returnValue(result)
def load_data(self, resource_name, timestamp, data):
"""Load data into a snapshot table.
Args:
resource_name (str): String of the resource name.
timestamp (str): String of timestamp, formatted as
YYYYMMDDTHHMMSSZ.
data (iterable): An iterable or a list of data to be uploaded.
Raises:
MySQLError: When an error has occured while executing the query.
"""
with csv_writer.write_csv(resource_name, data) as csv_file:
try:
snapshot_table_name = self._create_snapshot_table_name(
resource_name, timestamp)
load_data_sql = load_data_sql_provider.provide_load_data_sql(
resource_name, csv_file.name, snapshot_table_name)
LOGGER.debug('SQL: %s', load_data_sql)
cursor = self.conn.cursor()
cursor.execute(load_data_sql)
self.conn.commit()
# TODO: Return the snapshot table name so that it can be tracked
# in the main snapshot table.
except (DataError, IntegrityError, InternalError,
NotSupportedError, OperationalError,
ProgrammingError) as e:
raise MySQLError(resource_name, e)
def get_latest_snapshot_timestamp(self, statuses):
"""Select the latest timestamp of the completed snapshot.
Args:
statuses (tuple): The tuple of snapshot statuses to filter on.
Returns:
str: The string timestamp of the latest complete snapshot.
Raises:
MySQLError: When no rows are found.
"""
# Build a dynamic parameterized query string for filtering the
# snapshot statuses
if not isinstance(statuses, tuple):
statuses = ('SUCCESS',)
status_params = ','.join(['%s']*len(statuses))
filter_clause = SNAPSHOT_STATUS_FILTER_CLAUSE.format(status_params)
try:
cursor = self.conn.cursor()
cursor.execute(
select_data.LATEST_SNAPSHOT_TIMESTAMP + filter_clause, statuses)
row = cursor.fetchone()
if row:
return row[0]
raise NoResultsError('No snapshot cycle found.')
except (DataError, IntegrityError, InternalError, NotSupportedError,
OperationalError, ProgrammingError, NoResultsError) as e:
raise MySQLError('snapshot_cycles', e)
def execute(self, *args, **kwargs):
try:
result = self._cursor.execute(*args, **kwargs)
except MySQLdb.ProgrammingError as e:
raise MySQLdb.ProgrammingError(e.args[0], e.args[1] + '.\nSTATEMENT: {}'.format(self._cursor._last_executed))
except MySQLdb.OperationalError as e:
# Sometimes a MySQL session times out. In this case, we wish to reconnect, and reissue the query.
if e[0] == 2006:
self.connect()
result = self._cursor.execute(*args, **kwargs)
else:
raise MySQLdb.OperationalError(e.args[0], e.args[1] + '.\nSTATEMENT: {}'.format(self._cursor._last_executed))
return result
def execute(self, query, args=None):
try:
# args is None means no string interpolation
return self.cursor.execute(query, args)
except Database.OperationalError as e:
# Map some error codes to IntegrityError, since they seem to be
# misclassified and Django would prefer the more logical place.
if e.args[0] in self.codes_for_integrityerror:
six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
raise