I am trying to catch and count the duplicate entry exception :
1062 (23000): Duplicate entry '' for key 'tabale.item_UNIQUE'
Here is the code that will generate the duplicate Item exception:
stmt='INSERT INTO table.items(item) VALUES("iteratorI");'
try:
mc.execute(stmt)
conn.commit()
except pymysql.IntegrityError as e:
duplicateCounter=duplicateCounter+1
except Exception as ee:
otherErrors=otherErrors+1
I would like to be able to count duplicate item entry exceptions separately to keeping the count of other exceptions.
I want to make sure the exception that I am counting is about the duplicate entry and nothing else. The other issue is that currently duplicateCounter is ending up being zero although I am getting at least 10 1062 exceptions which are counted in otherErrors
You haven't really stated what your concern is. Is it that you are worried that the pymysql.IntegrityError
exception might be caused by something other than a duplicate key error? If that is the issue, you can check that the error code associated with the exception is 1062 (DUP_ENTRY) as follows:
stmt = 'INSERT INTO table.items(item) VALUES("iteratorI");'
try:
mc.execute(stmt)
conn.commit()
except pymysql.IntegrityError as e:
if e.args[0] == 1062:
duplicateCounter += 1
except Exception as ee:
otherErrors += 1
If you do not want to hard-code the value 1062
, you could ...
from pymysql.constants.ER import DUP_ENTRY
... and then compare e.args[0]
with DUP_ENTRY
. But you would then be substituting one coding dependency for another.