本文整理汇总了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'