Handling MySQL duplicate key errors separately from other exceptions in Python

Help needed with MySQL error handling in Python

I’m working on a Python script that inserts data into a MySQL database. I want to count duplicate key errors separately from other exceptions. Here’s what I’ve tried:

try:
    cursor.execute('INSERT INTO products(name) VALUES("laptop")')
    db.commit()
except pymysql.IntegrityError as e:
    duplicate_count += 1
except Exception as e:
    other_error_count += 1

The problem is that my duplicate_count stays at zero even though I’m getting several ‘1062’ errors. These errors are being counted as other exceptions instead.

How can I make sure I’m only counting the duplicate key errors (error code 1062) in the duplicate_count? And why aren’t they being caught by the IntegrityError exception?

Any help would be great. Thanks!

hey there! i had a similar issue. try catching pymysql.err.IntegrityError instead of just IntegrityError. also, check if the error code is 1062 like this:

if e.args[0] == 1062:
duplicate_count += 1

hope this helps! let me know if u need more info

I’ve dealt with this exact problem before in one of my projects. The key is to use the specific MySQL error code. Here’s what worked for me:

try:
cursor.execute(‘INSERT INTO products(name) VALUES(“laptop”)’)
db.commit()
except pymysql.err.MySQLError as e:
error_code = e.args[0]
if error_code == 1062:
duplicate_count += 1
else:
other_error_count += 1

This approach catches all MySQL errors and then checks for the specific duplicate key error code. It’s more robust and should solve your counting issue. Also, make sure you’re using the latest version of PyMySQL, as error handling can sometimes change between versions.

Remember to close your cursor and connection properly after you’re done with database operations to avoid resource leaks.