简体   繁体   中英

MySQLdb Error Handling in Python 2.7

Im pretty new to Python and have an SQL Insert statement that throws an exception due a to primary key violation:

File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 202, in execute
self.errorhandler(self, exc, value)
File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
_mysql_exceptions.IntegrityError: (1062, "Duplicate entry 'Y31 ROB' for key 'PRIMARY'")

How do you handle this error, so if it is thrown it exits the function?

I have tried:

try:
    webcur.execute("INSERT INTO foo VALUES bar")
except (MySQLdb.Error):
    return

and also:

except (MySQLdb.IntegrityError)

but neither seem to work.

Try assigning it to a variable like so:

try:
    webcur.execute("INSERT INTO foo VALUES bar")
except MySQLdb.Error as e:
    return

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM