mysqldb duplicate entry error handling

John Nagle nagle at animats.com
Fri Feb 2 02:53:05 EST 2007


Dennis Lee Bieber wrote:
> On 1 Feb 2007 10:17:31 -0800, "baur79" <baur79 at gmail.com> declaimed the
> following in comp.lang.python:

>>IntegrityError: (1062, "Duplicate entry 'email at domain.com' for key 1")
> 
> 	So show us the schema for the database... My take: Your database
> ALREADY HAS a record with that "email at domain.com" value AND emails.email
> is defined as a unique key field.

    Right.  That's not a bug; it's supposed to do that when you try
to add a duplicate.  What do you want to happen?

    If you want to allow duplicates, remove the UNIQUE on that
field from the schema.

    If you want the new entry to replace the old entry, use REPLACE
instead of INSERT.

    If you just want to detect the problem, provide

import MySQLdb
kmysqlduplicateentry = 1062	# MySQL error code when INSERT finds a duplicate
try :
	... # do INSERT
except MySQLdb.IntegrityError, message:			
	errorcode = message[0]	# get MySQL error code
	if errorcode == kmysqlduplicateentry :	# if duplicate
		... 			# handle duplicate
	else:
		raise			# unexpected error, reraise


					John Nagle



More information about the Python-list mailing list