This exception is the base class for all other exceptions in the
errors module. It can be used to catch all
errors in a single except statement.
The following example shows how we could catch syntax errors:
import mysql.connector
try:
cnx = mysql.connector.connect(user='scott', database='employees')
cursor = cnx.cursor()
cursor.execute("SELECT * FORM employees") # Syntax error in query
cnx.close()
except mysql.connector.Error as err:
print("Something went wrong: {}".format(err))
Initializing the exception supports a few optional arguments,
namely msg, errno,
values and sqlstate. All
of them are optional and default to None.
errors.Error is internally used by
Connector/Python to raise MySQL client and server errors and
should not be used by your application to raise exceptions.
The following examples show the result when using no arguments or a combination of the arguments:
>>> from mysql.connector.errors import Error
>>> str(Error())
'Unknown error'
>>> str(Error("Oops! There was an error."))
'Oops! There was an error.'
>>> str(Error(errno=2006))
'2006: MySQL server has gone away'
>>> str(Error(errno=2002, values=('/tmp/mysql.sock', 2)))
"2002: Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)"
>>> str(Error(errno=1146, sqlstate='42S02', msg="Table 'test.spam' doesn't exist"))
"1146 (42S02): Table 'test.spam' doesn't exist"
The example which uses error number 1146 is used when
Connector/Python receives an error packet from the MySQL Server.
The information is parsed and passed to the
Error exception as shown.
Each exception subclassing from Error can be
initialized using the previously mentioned arguments.
Additionally, each instance has the attributes
errno, msg and
sqlstate which can be used in your code.
The following example shows how to handle errors when dropping a
table which does not exist (when the DROP
TABLE statement does not include a IF
EXISTS clause):
import mysql.connector
from mysql.connector import errorcode
cnx = mysql.connector.connect(user='scott', database='test')
try:
cur.execute("DROP TABLE spam")
except mysql.connector.Error as err:
if err.errno == errorcode.ER_BAD_TABLE_ERROR:
print("Creating table spam")
else:
raise
errors.Error is a subclass of the Python
StandardError.

User Comments
Add your own comment.