本文整理匯總了Python中MySQLdb.Error方法的典型用法代碼示例。如果您正苦於以下問題:Python MySQLdb.Error方法的具體用法?Python MySQLdb.Error怎麽用?Python MySQLdb.Error使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類MySQLdb
的用法示例。
在下文中一共展示了MySQLdb.Error方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: connect
# 需要導入模塊: import MySQLdb [as 別名]
# 或者: from MySQLdb import Error [as 別名]
def connect(self, host=None, user=None, passwd=None, database=None):
'''Connect to the concrete data base.
The first time a valid host, user, passwd and database must be provided,
Following calls can skip this parameters
'''
try:
if host is not None: self.host = host
if user is not None: self.user = user
if passwd is not None: self.passwd = passwd
if database is not None: self.database = database
self.con = mdb.connect(self.host, self.user, self.passwd, self.database)
self.logger.debug("connected to DB %s at %s@%s", self.database,self.user, self.host)
return 0
except mdb.Error as e:
self.logger.error("Cannot connect to DB %s at %s@%s Error %d: %s", self.database, self.user, self.host, e.args[0], e.args[1])
return -1
示例2: get_db_version
# 需要導入模塊: import MySQLdb [as 別名]
# 或者: from MySQLdb import Error [as 別名]
def get_db_version(self):
''' Obtain the database schema version.
Return: (negative, text) if error or version 0.0 where schema_version table is missing
(version_int, version_text) if ok
'''
cmd = "SELECT version_int,version,openvim_ver FROM schema_version"
for retry_ in range(0,2):
try:
with self.con:
self.cur = self.con.cursor()
self.logger.debug(cmd)
self.cur.execute(cmd)
rows = self.cur.fetchall()
highest_version_int=0
highest_version=""
#print rows
for row in rows: #look for the latest version
if row[0]>highest_version_int:
highest_version_int, highest_version = row[0:2]
return highest_version_int, highest_version
except (mdb.Error, AttributeError) as e:
self.logger.error("get_db_version DB Exception %d: %s. Command %s",e.args[0], e.args[1], cmd)
r,c = self.format_error(e)
if r!=-HTTP_Request_Timeout or retry_==1: return r,c
示例3: __get_used_net_vlan
# 需要導入模塊: import MySQLdb [as 別名]
# 或者: from MySQLdb import Error [as 別名]
def __get_used_net_vlan(self):
#get used from database if needed
try:
cmd = "SELECT vlan FROM nets WHERE vlan>='%s' and (type='ptp' or type='data') ORDER BY vlan LIMIT 25" % self.net_vlan_lastused
with self.con:
self.cur = self.con.cursor()
self.logger.debug(cmd)
self.cur.execute(cmd)
vlan_tuple = self.cur.fetchall()
#convert a tuple of tuples in a list of numbers
self.net_vlan_usedlist = []
for k in vlan_tuple:
self.net_vlan_usedlist.append(k[0])
return 0
except (mdb.Error, AttributeError) as e:
return self.format_error(e, "get_free_net_vlan", cmd)
示例4: delete_row_by_key
# 需要導入模塊: import MySQLdb [as 別名]
# 或者: from MySQLdb import Error [as 別名]
def delete_row_by_key(self, table, key, value):
for retry_ in range(0,2):
cmd=""
try:
with self.con:
#delete host
self.cur = self.con.cursor()
cmd = "DELETE FROM %s" % (table)
if key!=None:
if value!=None:
cmd += " WHERE %s = '%s'" % (key, value)
else:
cmd += " WHERE %s is null" % (key)
else: #delete all
pass
self.logger.debug(cmd)
self.cur.execute(cmd)
deleted = self.cur.rowcount
if deleted < 1:
return -1, 'Not found'
#delete uuid
return 0, deleted
except (mdb.Error, AttributeError) as e:
r,c = self.format_error(e, "delete_row_by_key", cmd, "delete", 'instances' if table=='hosts' or table=='tenants' else 'dependencies')
if r!=-HTTP_Request_Timeout or retry_==1: return r,c
示例5: get_db_version
# 需要導入模塊: import MySQLdb [as 別名]
# 或者: from MySQLdb import Error [as 別名]
def get_db_version(self):
''' Obtain the database schema version.
Return: (negative, text) if error or version 0.0 where schema_version table is missing
(version_int, version_text) if ok
'''
cmd = "SELECT version_int,version,openmano_ver FROM schema_version"
for retry_ in range(0,2):
try:
with self.con:
self.cur = self.con.cursor()
#print cmd
self.cur.execute(cmd)
rows = self.cur.fetchall()
highest_version_int=0
highest_version=""
#print rows
for row in rows: #look for the latest version
if row[0]>highest_version_int:
highest_version_int, highest_version = row[0:2]
return highest_version_int, highest_version
except (mdb.Error, AttributeError), e:
#print cmd
print "get_db_version DB Exception %d: %s" % (e.args[0], e.args[1])
r,c = self.format_error(e)
if r!=-HTTP_Request_Timeout or retry_==1: return r,c
示例6: new_row
# 需要導入模塊: import MySQLdb [as 別名]
# 或者: from MySQLdb import Error [as 別名]
def new_row(self, table, INSERT, tenant_id=None, add_uuid=False, log=False, created_time=0):
''' Add one row into a table.
Attribute
INSERT: dictionary with the key: value to insert
table: table where to insert
tenant_id: only useful for logs. If provided, logs will use this tenant_id
add_uuid: if True, it will create an uuid key entry at INSERT if not provided
It checks presence of uuid and add one automatically otherwise
Return: (result, uuid) where result can be 0 if error, or 1 if ok
'''
if table in tables_with_created_field and created_time==0:
created_time=time.time()
for retry_ in range(0,2):
try:
with self.con:
self.cur = self.con.cursor()
return self._new_row_internal(table, INSERT, tenant_id, add_uuid, None, log, created_time)
except (mdb.Error, AttributeError), e:
print "nfvo_db.new_row DB Exception %d: %s" % (e.args[0], e.args[1])
r,c = self.format_error(e)
if r!=-HTTP_Request_Timeout or retry_==1: return r,c
示例7: update_rows
# 需要導入模塊: import MySQLdb [as 別名]
# 或者: from MySQLdb import Error [as 別名]
def update_rows(self, table, UPDATE, WHERE, log=False, modified_time=0):
''' Update one or several rows into a table.
Atributes
UPDATE: dictionary with the key: value to change
table: table where to update
WHERE: dictionary of elements to update
Return: (result, descriptive text) where result indicates the number of updated files
'''
if table in tables_with_created_field and modified_time==0:
modified_time=time.time()
for retry_ in range(0,2):
try:
with self.con:
self.cur = self.con.cursor()
return self.__update_rows(table, UPDATE, WHERE, log)
except (mdb.Error, AttributeError), e:
print "nfvo_db.update_rows DB Exception %d: %s" % (e.args[0], e.args[1])
r,c = self.format_error(e)
if r!=-HTTP_Request_Timeout or retry_==1: return r,c
示例8: update_datacenter_nets
# 需要導入模塊: import MySQLdb [as 別名]
# 或者: from MySQLdb import Error [as 別名]
def update_datacenter_nets(self, datacenter_id, new_net_list=[]):
''' Removes the old and adds the new net list at datacenter list for one datacenter.
Attribute
datacenter_id: uuid of the datacenter to act upon
table: table where to insert
new_net_list: the new values to be inserted. If empty it only deletes the existing nets
Return: (Inserted items, Deleted items) if OK, (-Error, text) if error
'''
for retry_ in range(0,2):
created_time = time.time()
try:
with self.con:
self.cur = self.con.cursor()
cmd="DELETE FROM datacenter_nets WHERE datacenter_id='%s'" % datacenter_id
print cmd
self.cur.execute(cmd)
deleted = self.cur.rowcount
for new_net in new_net_list:
created_time += 0.00001
self._new_row_internal('datacenter_nets', new_net, tenant_id=None, add_uuid=True, created_time=created_time)
return len (new_net_list), deleted
except (mdb.Error, AttributeError), e:
print "nfvo_db.update_datacenter_nets DB Exception %d: %s" % (e.args[0], e.args[1])
r,c = self.format_error(e)
if r!=-HTTP_Request_Timeout or retry_==1: return r,c
示例9: setUp
# 需要導入模塊: import MySQLdb [as 別名]
# 或者: from MySQLdb import Error [as 別名]
def setUp(self):
_skip_if_no_MySQLdb()
import MySQLdb
try:
# Try Travis defaults.
# No real user should allow root access with a blank password.
self.db = MySQLdb.connect(host='localhost', user='root', passwd='',
db='pandas_nosetest')
except:
pass
else:
return
try:
self.db = MySQLdb.connect(read_default_group='pandas')
except MySQLdb.ProgrammingError as e:
raise nose.SkipTest(
"Create a group of connection parameters under the heading "
"[pandas] in your system's mysql default file, "
"typically located at ~/.my.cnf or /etc/.my.cnf. ")
except MySQLdb.Error as e:
raise nose.SkipTest(
"Cannot connect to database. "
"Create a group of connection parameters under the heading "
"[pandas] in your system's mysql default file, "
"typically located at ~/.my.cnf or /etc/.my.cnf. ")
示例10: deprovision_mysql
# 需要導入模塊: import MySQLdb [as 別名]
# 或者: from MySQLdb import Error [as 別名]
def deprovision_mysql(self, ignore_errors=False):
"""
Drop all MySQL databases and users.
"""
self.logger.info('Deprovisioning MySQL started.')
if self.mysql_server and self.mysql_provisioned:
try:
cursor = _get_mysql_cursor(self.mysql_server)
# Drop default databases and users
for database in self.mysql_databases:
database_name = database["name"]
_drop_database(cursor, database_name)
_drop_user(cursor, database["user"])
# Drop users with global privileges
for user in self.global_users:
_drop_user(cursor, user)
except MySQLError:
if not ignore_errors:
raise
self.mysql_provisioned = False
self.save()
self.logger.info('Deprovisioning MySQL finished.')
示例11: _get_cursor
# 需要導入模塊: import MySQLdb [as 別名]
# 或者: from MySQLdb import Error [as 別名]
def _get_cursor(url):
"""
Returns a cursor on the database
"""
database_url_obj = urlparse(url)
try:
connection = mysql.connect(
host=database_url_obj.hostname,
user=database_url_obj.username or '',
passwd=database_url_obj.password or '',
port=database_url_obj.port or 3306,
)
except MySQLError as exc:
logger.exception('Cannot get MySQL cursor: %s', exc)
return None
return connection.cursor()
# Classes ####################################################################
示例12: _get_integration_databases
# 需要導入模塊: import MySQLdb [as 別名]
# 或者: from MySQLdb import Error [as 別名]
def _get_integration_databases(self):
"""
List of integration databases.
"""
if not self.cursor:
logger.error('ERROR: Not connected to the database')
return []
query = (
"SELECT Db from mysql.db where Db REGEXP 'integration_{domain_suffix}'".format(
domain_suffix=self.domain_suffix
)
)
try:
self.cursor.execute(query)
except MySQLError as exc:
logger.exception('Unable to retrieve integrations databases: %s', exc)
return []
return self.cursor.fetchall()
示例13: _get_db_users
# 需要導入模塊: import MySQLdb [as 別名]
# 或者: from MySQLdb import Error [as 別名]
def _get_db_users(self, hash_prefix):
"""
List of users filtering on a hash prefix.
Args:
hash_prefix (str): Hash prefix used to filter users.
Returs:
[tuple]: List of tuples with usernames.
"""
if not self.cursor:
logger.error('ERROR: Not connected to the database')
return []
prefix = "{hash_prefix}\\_%%".format(hash_prefix=hash_prefix)
try:
self.cursor.execute("SELECT User from mysql.user where User like %(prefix)s", {"prefix": prefix})
except MySQLError as exc:
logger.exception('Unable to retrieve old databases: %s', exc)
return []
return self.cursor.fetchall()
示例14: _drop_db
# 需要導入模塊: import MySQLdb [as 別名]
# 或者: from MySQLdb import Error [as 別名]
def _drop_db(self, database):
"""
Drop a single database.
Args:
database (str): Database name.
"""
if not self.dry_run:
try:
self.cursor.execute(
'DROP DATABASE IF EXISTS `{}`'.format(database)
)
except MySQLError as exc:
logger.exception(
'Unable to remove MySQL DB: %s. %s', database, exc
)
示例15: insert_into_db
# 需要導入模塊: import MySQLdb [as 別名]
# 或者: from MySQLdb import Error [as 別名]
def insert_into_db(sql,conn=None):
global dbconn
if (conn == None) :
if (dbconn == None ):
conn = connect_db()
else:
conn = dbconn
if (conn) :
try:
cursor = conn.cursor()
n = cursor.execute(sql)
conn.commit();
print n
except MySQLdb.Error,e:
#WARNING Mysql Error sql = 1062 Duplicate entry "***" for key 'unique_key'
if (e.args[0] == 1062):
return 0
warnString = " Mysql Error sql = %d %s " % (e.args[0],e.args[1])
log_init().warning(warnString)
if(e.args[0] == 2006):
return 2
else:
return 0