本文整理匯總了Python中MySQLdb.IntegrityError方法的典型用法代碼示例。如果您正苦於以下問題:Python MySQLdb.IntegrityError方法的具體用法?Python MySQLdb.IntegrityError怎麽用?Python MySQLdb.IntegrityError使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類MySQLdb
的用法示例。
在下文中一共展示了MySQLdb.IntegrityError方法的11個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: execute
# 需要導入模塊: import MySQLdb [as 別名]
# 或者: from MySQLdb import IntegrityError [as 別名]
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
示例2: executemany
# 需要導入模塊: import MySQLdb [as 別名]
# 或者: from MySQLdb import IntegrityError [as 別名]
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
示例3: check_constraints
# 需要導入模塊: import MySQLdb [as 別名]
# 或者: from MySQLdb import IntegrityError [as 別名]
def check_constraints(self, table_names=None):
"""
Checks each table name in `table_names` for rows with invalid foreign
key references. This method is intended to be used in conjunction with
`disable_constraint_checking()` and `enable_constraint_checking()`, to
determine if rows with invalid references were entered while constraint
checks were off.
Raises an IntegrityError on the first invalid foreign key reference
encountered (if any) and provides detailed information about the
invalid reference in the error message.
Backends can override this method if they can more directly apply
constraint checking (e.g. via "SET CONSTRAINTS ALL IMMEDIATE")
"""
cursor = self.cursor()
if table_names is None:
table_names = self.introspection.table_names(cursor)
for table_name in table_names:
primary_key_column_name = self.introspection.get_primary_key_column(cursor, table_name)
if not primary_key_column_name:
continue
key_columns = self.introspection.get_key_columns(cursor, table_name)
for column_name, referenced_table_name, referenced_column_name in key_columns:
cursor.execute("""
SELECT REFERRING.`%s`, REFERRING.`%s` FROM `%s` as REFERRING
LEFT JOIN `%s` as REFERRED
ON (REFERRING.`%s` = REFERRED.`%s`)
WHERE REFERRING.`%s` IS NOT NULL AND REFERRED.`%s` IS NULL"""
% (primary_key_column_name, column_name, table_name, referenced_table_name,
column_name, referenced_column_name, column_name, referenced_column_name))
for bad_row in cursor.fetchall():
raise utils.IntegrityError("The row in table '%s' with primary key '%s' has an invalid "
"foreign key: %s.%s contains a value '%s' that does not have a corresponding value in %s.%s."
% (table_name, bad_row[0],
table_name, column_name, bad_row[1],
referenced_table_name, referenced_column_name))
示例4: _crawl
# 需要導入模塊: import MySQLdb [as 別名]
# 或者: from MySQLdb import IntegrityError [as 別名]
def _crawl(self, mid, cur):
"""
抓取並持久化用戶信息
:param mid: B站用戶id
:param cur: mysql遊標
:return: None
"""
if self._is_member_exist(cur, mid):
print(f'數據庫中已存在此用戶mid:{mid}, 忽略')
return
member_info = self._get_member_by_mid(mid)
if member_info is None:
return
mid = member_info['mid']
name = member_info['name']
sign = member_info['sign'].replace("'", "\\\'")
rank = member_info['rank']
level = member_info['level']
jointime = member_info['jointime']
moral = member_info['moral']
silence = member_info['silence']
birthday = member_info['birthday']
coins = member_info['coins']
fans_badge = member_info['fans_badge']
vip_type = member_info['vip']['type']
vip_status = member_info['vip']['status']
try:
cur.execute(f"INSERT INTO bilibili_member "
f"(mid, name, sign, `rank`, `level`, jointime, moral, silence, birthday, coins, fans_badge, vip_type, vip_status) "
f"VALUES "
f"({mid}, '{name}', '{sign}', {rank}, {level}, {jointime}, {moral}, {silence}, '{birthday}', "
f"{coins}, {fans_badge}, {vip_type}, {vip_status})"
)
print(f'成功插入用戶數據: {mid}, 當前代理:{self.cur_proxy["https"]}')
except MySQLdb.ProgrammingError as e:
print(f'插入用戶: {mid} 數據出錯:{e}')
raise SqlInsertException(str(e))
except MySQLdb.IntegrityError:
print(f'用戶: {mid} 數據已存在,不作插入')
raise SqlAlreadyExistsException('數據已存在')
示例5: _insert_failure_record
# 需要導入模塊: import MySQLdb [as 別名]
# 或者: from MySQLdb import IntegrityError [as 別名]
def _insert_failure_record(cur, mid, state, remark):
remark = remark.replace("'", "\\\'")
try:
cur.execute(
"INSERT INTO failure_record (mid, remark, state) "
f"VALUES ({mid}, '{remark}', '{state}')"
)
except MySQLdb.ProgrammingError as e:
print(f'插入失敗日誌: {mid} 數據出錯:{e}')
except MySQLdb.IntegrityError:
print(f'失敗日誌: {mid} 數據已存在,不作插入')
示例6: delete
# 需要導入模塊: import MySQLdb [as 別名]
# 或者: from MySQLdb import IntegrityError [as 別名]
def delete(cls, id):
sql = 'delete from movie_order where id=%s'
try:
store.execute(sql, id)
store.commit()
except IntegrityError:
store.rollback()
return False
return True
示例7: delete
# 需要導入模塊: import MySQLdb [as 別名]
# 或者: from MySQLdb import IntegrityError [as 別名]
def delete(cls, id):
sql = 'delete from movie_order where id=%s'
try:
store.execute(sql, id)
store.commit()
except IntegrityError:
store.rollback()
return False
cls.clear_mc(id)
return True
示例8: execute
# 需要導入模塊: import MySQLdb [as 別名]
# 或者: from MySQLdb import IntegrityError [as 別名]
def execute(self, query, args=None):
try:
return self.cursor.execute(query, args)
except Database.IntegrityError as e:
six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
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])
six.reraise(utils.DatabaseError, utils.DatabaseError(*tuple(e.args)), sys.exc_info()[2])
except Database.DatabaseError as e:
six.reraise(utils.DatabaseError, utils.DatabaseError(*tuple(e.args)), sys.exc_info()[2])
示例9: executemany
# 需要導入模塊: import MySQLdb [as 別名]
# 或者: from MySQLdb import IntegrityError [as 別名]
def executemany(self, query, args):
try:
return self.cursor.executemany(query, args)
except Database.IntegrityError as e:
six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
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])
six.reraise(utils.DatabaseError, utils.DatabaseError(*tuple(e.args)), sys.exc_info()[2])
except Database.DatabaseError as e:
six.reraise(utils.DatabaseError, utils.DatabaseError(*tuple(e.args)), sys.exc_info()[2])
示例10: check_constraints
# 需要導入模塊: import MySQLdb [as 別名]
# 或者: from MySQLdb import IntegrityError [as 別名]
def check_constraints(self, table_names=None):
"""
Checks each table name in `table_names` for rows with invalid foreign key references. This method is
intended to be used in conjunction with `disable_constraint_checking()` and `enable_constraint_checking()`, to
determine if rows with invalid references were entered while constraint checks were off.
Raises an IntegrityError on the first invalid foreign key reference encountered (if any) and provides
detailed information about the invalid reference in the error message.
Backends can override this method if they can more directly apply constraint checking (e.g. via "SET CONSTRAINTS
ALL IMMEDIATE")
"""
cursor = self.cursor()
if table_names is None:
table_names = self.introspection.table_names(cursor)
for table_name in table_names:
primary_key_column_name = self.introspection.get_primary_key_column(cursor, table_name)
if not primary_key_column_name:
continue
key_columns = self.introspection.get_key_columns(cursor, table_name)
for column_name, referenced_table_name, referenced_column_name in key_columns:
cursor.execute("""
SELECT REFERRING.`%s`, REFERRING.`%s` FROM `%s` as REFERRING
LEFT JOIN `%s` as REFERRED
ON (REFERRING.`%s` = REFERRED.`%s`)
WHERE REFERRING.`%s` IS NOT NULL AND REFERRED.`%s` IS NULL"""
% (primary_key_column_name, column_name, table_name, referenced_table_name,
column_name, referenced_column_name, column_name, referenced_column_name))
for bad_row in cursor.fetchall():
raise utils.IntegrityError("The row in table '%s' with primary key '%s' has an invalid "
"foreign key: %s.%s contains a value '%s' that does not have a corresponding value in %s.%s."
% (table_name, bad_row[0],
table_name, column_name, bad_row[1],
referenced_table_name, referenced_column_name))
示例11: dbupdate
# 需要導入模塊: import MySQLdb [as 別名]
# 或者: from MySQLdb import IntegrityError [as 別名]
def dbupdate(db,tablename, keys, values, condition=None):
"""
DEFINITION:
Perform an update call to add values into specific keys of the selected table
PARAMETERS:
Variables:
- db: (mysql database) defined by mysql.connect().
- tablename: name of the table
- keys: (list) list of keys to modify
- values: (list) list of values for the keys
Kwargs:
- condition: (string) put in an optional where condition
APPLICATION:
>>>dbupdate(db, 'DATAINFO', [], [], condition='SensorID="MySensor"')
returns a string with either 'success' or an error message
"""
try:
if not len(keys) == len(values):
print("dbupdate: amount of keys does not fit provided values")
return False
except:
print("dbupdate: keys and values must be provided as list e.g. [key1,key2,...]")
if not len(keys) > 0:
print("dbupdate: provide at least on key/value pair")
return False
if not condition:
condition = ''
else:
condition = 'WHERE %s' % condition
setlist = []
for idx,el in enumerate(keys):
st = '%s="%s"' % (el, values[idx])
setlist.append(st)
if len(setlist) > 0:
setstring = ','.join(setlist)
else:
setstring = setlist[0]
updatesql = 'UPDATE %s SET %s %s' % (tablename, setstring, condition)
cursor = db.cursor()
print(updatesql)
try:
cursor.execute(updatesql)
except mysql.IntegrityError as message:
return message
except mysql.Error as message:
return message
except:
return 'dbupdate: unkown error'
db.commit()
cursor.close()
return 'success'