我正在使用以下模块生成唯一ID。但是每天它会为第一笔贷款抛出IntegrityError: (1062, "Duplicate entry '122830001' for key 'PRIMARY'")
。
我无法找到问题的原因。请帮帮忙?
def generate_loanid(leadid='0', counter=0):
""" Locks the customer_loanid table retrieves maximum loanid from it.
Generates a new loanid and puts it back in the table.
Returns the new loanid.
"""
def gen_id(max_loanid=0, count=0):
"""
Increments the counter if an id exists for the day.
Else resets the counter and creates a fresh one.
"""
timestamp_now = time.localtime()
if max_loanid:
logger.debug("""Current Maximum Loan id :
(Year(YY)+Julian Day(DDD)+Counter(CCCC) %d,
Current timestamp : %s""" %(max_loanid, timestamp_now))
julian_day = (max_loanid/10000) % 1000
if julian_day == timestamp_now[7]:
count = max_loanid % 10000
return (str(timestamp_now[0])[2:] +
str(timestamp_now[7]).rjust(3, '0') +
str(count+1).rjust(4, '0')
)
logger.debug("Leadid:%s - Counter:%s"%(leadid, counter))
db_obj = dbLis(pooling=False)
try:
try:
db_obj.query("lock tables customer_loanid write")
max_loanid = db_obj.query("select max(loanid) as loanid from customer_loanid")
curr_loanid = gen_id(max_loanid = max_loanid.__len__() and max_loanid[0].loanid)
db_obj.insert('customer_loanid', loanid=curr_loanid)
except (MySQLdb.IntegrityError,MySQLdb.OperationalError):
logger.warning(traceback.format_exc())
#There is no logical backing for this piece of code.
if counter < 3:
db_obj.query("unlock tables")
return generate_loanid(counter=counter+1)
else:
raise
finally:
try:
db_obj.query("unlock tables")
logger.debug("Unlocked All Tables")
db_obj.ctx.db.close()
except MySQLdb.OperationalError:
logger.info("Table unlocked already")
logger.debug(traceback.format_exc())
logger.info("Generated Loanid : %s"%(curr_loanid))
return curr_loanid
表格结构:
CREATE TABLE `customer_loanid` (
`loanid` int(15) NOT NULL DEFAULT '0',
PRIMARY KEY (`loanid`)
)
答案 0 :(得分:1)
您可以在一个查询中完成所有操作:
timestamp_now = time.localtime()
day_part_of_id = str(timestamp_now[0])[2:] + str(timestamp_now[7]).rjust(3, '0')
min_id_of_day = day_part_of_id + '0001'
sql = "INSERT INTO customer_loanid (SELECT "+min_id_of_day+" + count(*) FROM customer_loanid WHERE loanid LIKE '"+day_part_of_id+"%'"