Adrian Adrian - 13 days ago 5
MySQL Question

How to get the MySQL type of error with PyMySQL?

I'm doing a Python application with MySQL and PyMySQL and I'd like to be able to know the number of the MySQL error when I get one so that I can do something different depending on it.

Is there a way to do that with a try-except statement or another way?

Answer

Any exception in Python has an args member that shows you how it was constructed. For example:

>>> e = Exception(1, 2, 3, 4)
>>> e.args
(1, 2, 3, 4)

For pymysql, they're always constructed with (errno, errorvalue). So:

try:
    do_stuff()
except MySQLError as e:
    print('Got error {!r}, errno is {}'.format(e, e.args[0]))

I'm not sure this is guaranteed by the documentation, but you can see how it works pretty easily from the source.

Comments